← Back to Docs
Recipe

Dockerfile Best Practices

Build minimal, cache-efficient, and secure container images for production workloads.

1. Pin Your Base Image

Use digest-pinned base images instead of floating tags. FROM node:20-slim@sha256:abc... guarantees reproducibility and prevents supply-chain drift.

2. Layer Ordering Matters

Place infrequently-changing instructions first. Copy package.json and run npm ci before copying source code. This maximizes Docker's build cache and slashes rebuild times.

3. Multi-Stage Builds

Compile in a builder stage, then copy only the runtime artifact into a slim final image. Your production container should never ship a compiler, dev headers, or build toolchain.

4. Run as Non-Root

Create a dedicated user with USER 1001. Never run containers as root in production — it's the single highest-impact security hardening step.

5. Minimize Layer Count

Chain RUN commands with && and clean up package caches in the same layer. Each RUN creates a new layer — fewer layers means smaller images and faster pulls.

6. Use .dockerignore

Exclude node_modules, .git, and local env files from the build context. A lean context speeds up builds and prevents accidental secret leakage.

7. HEALTHCHECK for Resilience

Define a HEALTHCHECK instruction so orchestrators can detect stalled containers. A simple curl against a readiness endpoint is often sufficient.

Pro tip: Combine these practices with Meridian's container scanning to catch misconfigurations before they reach production.