CodeBlanks Logo Icon CodeBlanks

Summary - Dockerfile

Combine FROM, RUN, COPY and CMD to write a Dockerfile.

Summary: the Dockerfile

In this group:

  • A Dockerfile describes an image with instructions from top to bottom; the first instruction is FROM.
  • The base image is pinned by version; -slim/-alpine reduce the size.
  • Each RUN is a layer; installing and cleaning up happen in the same RUN.
  • COPY copies from the context; the dependency file is copied before the code.
  • CMD is the default command, ENTRYPOINT the fixed program; the exec form is preferred.
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["python", "app.py"]

Practice A complete Python Dockerfile

Write a Dockerfile based on python:3.12-slim with working directory /app: copy requirements.txt and run pip install --no-cache-dir -r requirements.txt; copy the whole project; document port 8000; CMD is python app.py in exec form.

Starter code

terminal
# buraya yaz

Sample solution

terminal
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["python", "app.py"]

Expected output

[+] Building 4.2s (8/8) FINISHED
 => naming to docker.io/library/api:latest done

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the drawback of a shell-form CMD?

  • It produces a bigger image
  • It can't use environment variables
  • It slows the build
  • The application may not receive SIGTERM and can't shut down cleanly Correct answer

Explanation: In shell form PID 1 is /bin/sh.

2 Set the working directory.

Question
____ /app
Answer
WORKDIR /app

Explanation: WORKDIR creates the directory if missing and sets it for the following instructions.

3 Match.

Term Meaning
FROM First instruction
RUN Build layer
EXPOSE Port documentation
CMD Default command

All lessons in Beginner