Summary - Dockerfile
- Docker & Kubernetes course
- Beginner
- Lesson 24/82
- 5 min
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/-alpinereduce the size. - Each
RUNis a layer; installing and cleaning up happen in the same RUN. COPYcopies from the context; the dependency file is copied before the code.CMDis the default command,ENTRYPOINTthe 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
# buraya yazSample solution
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.
____ /app
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 |