Skip to content

Instantly share code, notes, and snippets.

@MrModest
Last active January 23, 2026 11:40
Show Gist options
  • Select an option

  • Save MrModest/356110c8e8e3dee139f78400415d77c4 to your computer and use it in GitHub Desktop.

Select an option

Save MrModest/356110c8e8e3dee139f78400415d77c4 to your computer and use it in GitHub Desktop.
Complete Production-Ready Dockerfile Rules

TLDR of the video: My Production Dockerfile Rules: How I Build Docker Images
Transcript from the author: My Production Dockerfile Rules: How I Build Docker Images


πŸ” Complete Production-Ready Dockerfile Rules

🧱 1. Base Image Selection

  • Use minimal base images β€” containers are not full VMs; only include needed runtime deps.
  • Prefer Alpine/slim/distroless/scratch when possible.
  • Derive the version from your project, don’t guess (e.g., use node:20-alpine if package.json says Node 20).

🧠 2. Build Optimization & Layer Caching

  • Use multi-stage builds so build tools and source don’t end up in runtime image.

  • Structure Dockerfile for cache friendliness:

    • Put rare-changing files (e.g., manifests) first.
    • Copy code later so changes don’t bust earlier cache.
  • Combine related RUN commands to reduce layers.

  • Clean caches in the same RUN layer where they’re created or you save nothing.


πŸ“ 3. Copying Files Intentionally

  • Avoid COPY . . β€” it brings in unwanted files, including secrets.
  • Be explicit: e.g., COPY src/ ./src/, COPY static/ ./static/.

πŸ“¦ 4. Dependencies

  • Install only production dependencies; e.g., npm ci --omit=dev.
  • Dev/test deps belong in build stage only.

πŸ”’ 5. Security Hardening

  • Never run as root β€” create and switch to a non-root user.
  • Pin base image versions β€” avoid :latest so builds are reproducible.
  • Prefer Official or Verified images; avoid random ones.
  • No secrets in images β€” environment vars or build args are safer.
  • No sudo in containers.
  • Install only necessary packages (e.g., use --no-install-recommends when using apt).
  • No debugging tools in production images β€” attackers love them.
  • If debugging is needed, use ephemeral debug containers instead.
  • Ensure runtime binaries are owned by root but executed by non-root so attackers can’t modify them.

πŸš€ 6. Runtime CMD & Execution

  • Always use the exec (JSON) form for CMD so signals (e.g., SIGTERM) are delivered correctly.

πŸ“Š 7. Maintainability Best Practices

  • Sort multi-line arguments alphabetically (e.g., package lists) to reduce diffs and merge conflicts.
  • Use WORKDIR instead of RUN cd …; WORKDIR persists across instructions.
  • Comment non-obvious decisions, not the obvious commands.
  • Add OCI labels like org.opencontainers.image.source, version, description for better image management.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment