The Dockerfile

Writing an image recipe and building it.

A Dockerfile is a text file with the instructions used to build an image. The instructions run in order, and most of them add a layer. The build is started with docker build, and the last argument is the context: the folder whose files may be copied into the image.

The main instructions: FROM chooses the base image, WORKDIR sets the working folder inside the image, COPY copies files from the context, RUN executes a command during the build and saves the result in a layer, and CMD sets the command that runs when the container starts. It is important not to confuse RUN and CMD: the first runs once during the build, the second at every start.

A small Python application:

FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["python", "main.py"]
docker build -t notes-api:0.1 .
docker run --rm notes-api:0.1

The dot at the end of docker build is the context, the current folder. The -t flag gives the image a name and a tag.

COPY only sees files inside the context. A path like COPY ../config.yml . will not work: everything the image needs must be in the folder passed to docker build. Relative destination paths are resolved from WORKDIR, so COPY . . copies the context into /app.

A common mistake is to start the service in RUN, for example RUN python main.py. The build hangs or finishes, and the image keeps only the result of the command, not a running process. Everything that should run after the container starts goes into CMD. Another mistake is to change an image by hand through docker exec and hope the changes survive: the right way is to fix the Dockerfile and rebuild.

Practice

  1. RUN and CMD

    How does RUN differ from CMD in a Dockerfile?

    • No difference, they are synonyms
    • RUN runs during the build, CMD when the container starts
    • RUN runs at every start, CMD once during the build
    • CMD installs packages, RUN starts the service
  2. The build context

    The build was started with docker build -t app . from the project folder. What is true? Mark all.

    • The dot at the end sets the build context
    • COPY can take a file from a folder above the context
    • The -t flag sets the image name
    • COPY . . copies the context into the current WORKDIR
  3. The first instruction

    Which instruction usually starts a Dockerfile and chooses the base image? Write its name.