What makes a good Dockerfile? Give some best practices.
BeginnerConceptContainers & Kubernetes basics
Answer
In one line: A good Dockerfile produces a small, secure, fast-building image: use a minimal pinned base image, order layers for caching, use multi-stage builds, run as a non-root user and never put secrets in the image.
Best practices:
- Use a small, trusted, pinned base image —
node:20-alpine,python:3.12-slim, distroless or Chainguard images. Avoidlatest. - Order instructions for caching — copy dependency files and install dependencies before copying the rest of the source, so code changes don't reinstall everything.
- Multi-stage builds — build in one stage with all the tools, copy only the final output into a small runtime image.
- Run as non-root — add a user and switch to it with
USER. - No secrets in the image — no API keys in
ENVor copied files; use runtime secrets or BuildKit secret mounts for build-time secrets. - Use
.dockerignore— exclude.git,node_modules, test files and local env files. - Combine and clean up in
RUN— fewer layers and no package caches left behind. - One main process per container, with a proper
CMD/ENTRYPOINTin exec form. - Add a
HEALTHCHECK(or use Kubernetes probes). - Scan the image (Trivy) and keep the base image updated.
Example (multi-stage Node.js):
# Build stage
FROM node:20-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
# Runtime stage
FROM node:20-alpine
WORKDIR /app
ENV NODE_ENV=production
COPY package*.json ./
RUN npm ci --omit=dev && npm cache clean --force
COPY --from=build /app/dist ./dist
USER node
EXPOSE 3000
CMD ["node", "dist/server.js"]
Result: a smaller image, fewer vulnerabilities (no build tools in production), faster pulls and safer runtime.
Tip for interviews: mention specific numbers if you have them — "multi-stage build cut our image from 1.1 GB to 180 MB."
More on Containers & Kubernetes basics
What is the difference between a Docker image and a container?BeginnerWhat is Kubernetes, and why do we need it?BeginnerExplain the Kubernetes architecture in simple terms.BeginnerWhat are Pods, Deployments and Services in Kubernetes?BeginnerWhat are liveness, readiness and startup probes?BeginnerWhat are resource requests and limits in Kubernetes?Beginner