🎓 A1Learner
🔍
0 of 50 lessons completed

Dockerfile Best Practices

Dockerfile best practices are a short list: small base images, one main process, no secrets in layers, and a named user. Each rule keeps the image small, clear and safe.

A tidy Dockerfile

Small base, pinned tag, named user, one process.

FROM python:3.12-slim
WORKDIR /app
COPY app.py .
RUN useradd -m app
USER app
CMD ["python", "app.py"]

Example

docker build -t g4-tidy:1.0 . >/dev/null
docker run --rm g4-tidy:1.0

Key points

  • Use a small base image, like python:3.12-slim or alpine.
  • Run one main process per container, so logs and restarts stay clear.
  • Never bake a secret into a layer. Pass it at run time.
  • Pin the base image tag, so a rebuild uses the same base.
  • Run as a named user, with a USER line, not as root.
  • Use .dockerignore to keep the context small and secrets out.

In this example, a tidy Dockerfile builds and runs. The base is small and pinned, the app runs as a named user, and one process runs in the container. The printed line proves the tidy image still runs.

Note

A best practice is a habit, not a rule the build enforces. The build passes either way.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Rust Playground

Exercise

Why run one main process per container?