Docker Dockerfiles Dockerfiles best pratices

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Group common operations

Docker builds images as a collection of layers. Each layer can only add data, even if this data says that a file has been deleted. Every instruction creates a new layer. For example:

RUN apt-get -qq update
RUN apt-get -qq install some-package

Has a couple of downsides:

  • It will create two layers, producing a larger image.
  • Using apt-get update alone in a RUN statement causes caching issues and subsequently apt-get install instructions may fail. Suppose you later modify apt-get install by adding extra packages, then docker interprets the initial and modified instructions as identical and reuses the cache from previous steps. As a result the apt-get update command is not executed because its cached version is used during the build.

Instead, use:

RUN apt-get -qq update && \
    apt-get -qq install some-package

as this only produce one layer.

Mention the maintainer

This is usually the second line of the Dockerfile. It tells who is in charge and will be able to help.

LABEL maintainer John Doe <[email protected]>

If you skip it, it will not break your image. But it will not help your users either.

Be concise

Keep your Dockerfile short. If a complex setup is necessary, consider using a dedicated script or setting up base images.



Got any Docker Question?