Container Build & Stack Quick Reference

Dockerfile, Multi-Stage Builds & Docker Compose Cheat Sheet

A great Dockerfile builds fast, small, and secure images using layer caching and multi-stage builds. Docker Compose (compose.yaml) wires your app, database, and networks together with one command.

⏱️ 8 min reference🟢 Beginner Friendly📅 Updated: 2026

Anatomy of a Multi-Stage Copy

COPY --from=builder /app/dist /usr/share/nginx/html
Instruction COPY Copies files into the final image
Stage Flag --from=builder Pulls artifacts from Stage 1
Source Path /app/dist Compiled output only (no source/SDK)
Destination /usr/share/nginx/html Where the slim runtime serves it
Multi-Stage Build: Shrink Images by 80–95% Builder Stage → Slim Runtime Image
STAGE 1: BUILDER (AS builder) node:22 / golang:1.23 (~900 MB) Compilers, devDeps, source code Outputs: /app/dist (artifact) COPY --from SDK & build tools left behind STAGE 2: FINAL RUNTIME alpine / distroless (~25 MB) Only /app/dist + runtime USER nonroot (secure) PROD IMAGE Fast push/pull Tiny attack surface

1 Dockerfile Instructions & Caching Order

Docker caches each instruction as a read-only layer. Put things that rarely change (base image, OS packages, dependency manifests) at the top, and things that change every commit (your app source code) near the bottom.

Memory Trick — Cache Invalidation Dominoes: When one line changes, Docker rebuilds that layer and every line below it. Always copy package.json / requirements.txt and run install before COPY . . so code edits skip reinstalling dependencies!

Essential Instructions (Top to Bottom Order)

Instruction What It Does Best Practice Example
FROM Sets the base image (or starts a new build stage). FROM node:22-alpine AS builder
WORKDIR Creates & sets the active directory inside the image. WORKDIR /app (avoid RUN cd ...)
COPY Copies local files/folders into the image. COPY package*.json ./
RUN Executes a shell command during build & commits a layer. RUN npm ci --omit=dev
ENV Sets persistent environment variables at build & runtime. ENV NODE_ENV=production
USER Switches from root to a non-privileged user. USER node
EXPOSE Documents which port the container listens on (metadata only). EXPOSE 3000
CMD Default command when the container starts (easily overridden). CMD ["node", "server.js"]

COPY vs ADD & CMD vs ENTRYPOINT

Comparison Option A Option B Rule of Thumb
Copying Files COPY src/ dest/
Predictable, copies local files & --from stages.
ADD src/ dest/
Auto-extracts local .tar archives & fetches URLs.
Use COPY 99% of the time. Only use ADD when you specifically want tar auto-extraction.
Startup Command CMD ["npm", "start"]
Default command; replaced if you pass args to docker run.
ENTRYPOINT ["python3"]
Fixed executable; args passed to docker run get appended.
Always use JSON exec form ["bin", "arg"] so SIGTERM stops the app cleanly.

2 Multi-Stage Build & .dockerignore Templates

Copy these production-ready templates directly into your project. A .dockerignore file keeps your build context tiny and prevents secrets like .env from leaking into image layers.

Dockerfile — Multi-Stage Node.js / Frontend Build
# Stage 1: Build with full Node toolchain
FROM node:22-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

# Stage 2: Serve static assets in a tiny Nginx image
FROM nginx:1.27-alpine AS runtime
COPY --from=builder /app/dist /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
.dockerignore — Keep Build Context Fast & Secret-Free
.git
.gitignore
node_modules
dist
build
.env
.env.*
*.log
.DS_Store
Dockerfile
compose.yaml

3 Docker Compose (compose.yaml) Anatomy

Modern Docker Compose uses compose.yaml (no top-level version: key needed). Every service in the same Compose file joins a shared bridge network automatically, so your API can reach Postgres at hostname db.

compose.yaml — API + PostgreSQL with Healthcheck & Named Volume
services:
  api:
    build: .
    ports:
      - "3000:3000"
    environment:
      DATABASE_URL: postgres://app:secret@db:5432/appdb
    depends_on:
      db:
        condition: service_healthy
    networks:
      - backend

  db:
    image: postgres:16-alpine
    environment:
      POSTGRES_USER: app
      POSTGRES_PASSWORD: secret
      POSTGRES_DB: appdb
    volumes:
      - pg_data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U app -d appdb"]
      interval: 5s
      timeout: 3s
      retries: 5
    networks:
      - backend

volumes:
  pg_data:

networks:
  backend:
Key Purpose Beginner Gotcha
services Defines each container in your stack (e.g., api, db). Service names double as internal DNS hostnames.
ports Maps HOST:CONTAINER ports (e.g., "8080:3000"). Only needed for services you access from outside Docker.
volumes Persists data outside the container (named volumes or bind mounts). Named volumes must also be declared under top-level volumes:.
networks Isolates groups of containers on custom virtual networks. Default network exists automatically; custom networks improve isolation.
depends_on Controls startup order between services. Plain depends_on only waits for container start, not DB readiness—pair with condition: service_healthy.
healthcheck Runs a probe inside the container to mark it healthy. Use lightweight tools already inside the image (pg_isready, curl).

4 Docker Compose CLI Commands

Use docker compose (with a space—Compose V2) rather than the legacy hyphenated docker-compose binary.

docker compose up -d --build
Start Stack in Background & Rebuild Images Reads compose.yaml, rebuilds changed Dockerfiles, and starts all services detached (-d).
docker compose ps
List Stack Containers & Health Status Shows running state, healthcheck status (healthy), and mapped ports.
docker compose logs -f api
Follow Live Logs for a Service Omit api to tail logs from all services together. Press Ctrl+C to stop watching.
docker compose exec api sh
Open a Shell Inside a Running Service Targets the Compose service name directly—no need to look up container IDs.
docker compose build --no-cache
Force a Clean Rebuild Ignores cached layers when debugging stale packages or build artifacts.
docker compose down
Stop & Remove Containers & Networks Safely tears down the stack while keeping named volumes intact.
docker compose down -v
Tear Down Stack & Delete Volumes Destroys containers, networks, and all named volumes (fresh database reset).

5 Danger Zone & Beginner Traps

⚠️ Watch Out Before You Build or Run
1. Using :latest Tag in Production

FROM node:latest or image: postgres:latest can silently pull a breaking major upgrade on the next rebuild. Always pin explicit versions like node:22.11-alpine or postgres:16-alpine.

2. Running Containers as root Instead of USER

Without a USER instruction, your app runs as UID 0 (root). If an attacker exploits your app, they have root privileges inside the container. Add USER node or USER 1001 before CMD.

3. Running docker compose down -v Carelessly

The -v flag permanently deletes every named volume defined in compose.yaml—including your Postgres/MySQL database data. Use plain docker compose down for normal restarts.

4. Missing .dockerignore Leaking .env & node_modules

Running COPY . . without a .dockerignore copies local secrets (.env), .git/ history, and host-compiled node_modules straight into your image.