Docker interview question · Most asked
What are Dockerfile best practices for production images?
Summary
Use a small, trusted, pinned base image; use multi-stage builds; order instructions for caching; combine package installs with cleanup in one layer; use a .dockerignore; run as a non-root user; use exec-form entrypoints; add a health check where the platform uses it; never bake secrets into images; and label images with source and version metadata.
Longer Answer
More details:
- Pin base images by version, and in high-security setups by digest (
python:3.12-slim@sha256:...), and rebuild regularly to pick up patches. apt-get update && apt-get install -y --no-install-recommends ... && rm -rf /var/lib/apt/lists/*in a singleRUN.COPYrather thanADDunless you need its extras.USER 10001(and files owned appropriately) so a container escape starts unprivileged.- One process per container; configuration from environment variables.
- Lint with hadolint and scan with Trivy or Docker Scout in CI.
Key Points
- Small pinned base; multi-stage.
- Cache-friendly order; single-layer cleanup.
- Non-root; exec form; no secrets.
- Lint and scan in CI.
More most-asked Docker questions
- How do you secure Docker containers and images?
- What is a container, and how does it differ from a virtual machine?
- What is the difference between an image and a container, and how do image layers work?
- CMD or ENTRYPOINT: what is the difference, and what are exec and shell forms?
- How does Docker build caching work, and how do you order a Dockerfile to use it well?
- ARG or ENV: what is the difference, and how do you pass secrets into a build safely?
- What are multi-stage builds, and why use them?
- How do you make Docker images smaller?