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.
Anatomy of a Multi-Stage Copy
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.
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.
# 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;"]
.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.
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 --buildcompose.yaml, rebuilds changed Dockerfiles, and starts all
services detached (-d).
docker compose pshealthy), and mapped
ports.
docker compose logs -f apiapi to tail logs from all services together. Press Ctrl+C to stop
watching.
docker compose exec api shdocker compose build --no-cachedocker compose downdocker compose down -v5 Danger Zone & Beginner Traps
: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.
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.
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.
.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.