Interview Prep/DevOps Fundamentals/Containers & Kubernetes basics

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:

  1. Use a small, trusted, pinned base image — node:20-alpine, python:3.12-slim, distroless or Chainguard images. Avoid latest.
  2. Order instructions for caching — copy dependency files and install dependencies before copying the rest of the source, so code changes don't reinstall everything.
  3. Multi-stage builds — build in one stage with all the tools, copy only the final output into a small runtime image.
  4. Run as non-root — add a user and switch to it with USER.
  5. No secrets in the image — no API keys in ENV or copied files; use runtime secrets or BuildKit secret mounts for build-time secrets.
  6. Use .dockerignore — exclude .git, node_modules, test files and local env files.
  7. Combine and clean up in RUN — fewer layers and no package caches left behind.
  8. One main process per container, with a proper CMD/ENTRYPOINT in exec form.
  9. Add a HEALTHCHECK (or use Kubernetes probes).
  10. 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."

All DevOps Fundamentals questions

More on Containers & Kubernetes basics