Skip to content

Writing a Dockerfile

A Dockerfile is a recipe for an image. Here’s a small Python web app:

Dockerfile
FROM python:3.12-slim
WORKDIR /app
# Dependencies first: this layer is cached until requirements.txt changes
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Code last: it changes most often
COPY . .
# Never run as root inside the container
RUN useradd --create-home appuser
USER appuser
EXPOSE 8000
CMD ["python", "-m", "http.server", "8000"]

Build and run it:

Terminal window
docker build -t myapp:1.0 .
docker run --rm -p 8000:8000 myapp:1.0

Everything in the directory is sent to the builder. Add a .dockerignore:

.dockerignore
.git
node_modules
__pycache__
.env

Check your understanding

1. Why copy requirements.txt and install dependencies before copying the rest of the code?
2. What does the USER instruction protect against?