Overview of best practices for writing Dockerfiles
This topic covers recommended best practices and methods for building efficient images. It provides general guidelines for your Dockerfiles and more specific best practices for each Dockerfile instruction.
Docker builds images automatically by reading the instructions from a Dockerfile which is a text file that contains all commands, in order, needed to build a given image. A Dockerfile adheres to a specific format and set of instructions which you can find at Dockerfile reference.
A Docker image consists of read-only layers each of which represents a Dockerfile instruction. The layers are stacked and each one is a delta of the changes from the previous layer.
# syntax=docker/dockerfile:1 FROM ubuntu:22.04 COPY . /app RUN make /app CMD python /app/app.py
In the example above, each instruction creates one layer:
FROMcreates a layer from the
COPYadds files from your Docker client's current directory.
RUNbuilds your application with
CMDspecifies what command to run within the container.
When you run an image and generate a container, you add a new writable layer, also called the container layer, on top of the underlying layers. All changes made to the running container, such as writing new files, modifying existing files, and deleting files, are written to this writable container layer.
- Dockerfile reference
- More about Automated builds
- Guidelines for creating Docker Official Images
- Best practices to containerize Node.js web applications with Dockeropen_in_new
- More about base images
- More on image layers and how Docker builds and stores images.
These Official Images have exemplary Dockerfiles: