This lesson combines 2 topics: Writing Dockerfiles and Docker Compose.
Learning Objectives
- Understand the syntax and role of each Dockerfile instruction
- Write Dockerfiles for Node.js and Python apps
- Optimize layer caching to reduce build time
- Apply multi-stage builds to reduce image size
- Know the best practices: alpine base, non-root user, .dockerignore, COPY vs ADD
- Understand the problem Docker Compose solves when running multi-container apps
- Know the
docker-compose.ymlsyntax (compose spec) - Understand default networking between services
- Use volumes to persist data
- Manage environment variables and secrets in Compose
- Build a full example app: web + Postgres + Redis
Part 1: Writing Dockerfiles
1. Dockerfile structure
# Comment
# ARG instruction (the only one allowed before FROM)
ARG NODE_VERSION=24
# Base image
FROM node:${NODE_VERSION}-alpine
# Metadata
LABEL maintainer="dev@example.com"
LABEL version="1.0"
# Set the working directory inside the container
WORKDIR /app
# Copy files from the build context into the container
COPY package*.json ./
# Run a command at build time
RUN npm ci --omit=dev
COPY . .
# Expose port (documentation only — does not actually open the port)
EXPOSE 3000
# Default environment variable
ENV NODE_ENV=production
# Non-root user
USER node
# Command run when the container starts
CMD ["node", "server.js"]
2. Key instructions
FROM — Base image
# Specific tag (recommended for production)
FROM node:24-alpine3.22
# Multi-stage: name the stage
FROM node:24-alpine AS builder
FROM python:3.12-slim AS runtime
# Use ARG before FROM (build-time variable)
ARG PYTHON_VERSION=3.12
FROM python:${PYTHON_VERSION}-slim
RUN — Run a command at build time
# One command per RUN — creates many layers, wastes cache
RUN apt-get update
RUN apt-get install -y curl
RUN rm -rf /var/lib/apt/lists/* # 3rd layer — CANNOT remove files from layers 1 and 2!
# Combine into one RUN — one layer, the correct pattern
RUN apt-get update && \
apt-get install -y --no-install-recommends curl vim && \
rm -rf /var/lib/apt/lists/*
# Use a heredoc (Docker BuildKit — supported since 2022)
RUN <<EOF
apt-get update
apt-get install -y curl
rm -rf /var/lib/apt/lists/*
EOF
COPY vs ADD
# COPY: simple, only copies files/directories — RECOMMENDED
COPY src/ /app/src/
COPY package.json package-lock.json ./
# ADD: has extra features — rarely used
# - Auto-extracts .tar.gz
# - Can COPY from a URL (NOT recommended — cannot be cached)
ADD https://example.com/file.tar.gz /tmp/ # bad practice
ADD local-archive.tar.gz /app/ # OK if you need extraction
# Best practice: always use COPY unless you need an ADD-specific feature
ENV and ARG
# ARG: only available at build time
ARG BUILD_VERSION=1.0.0
# ENV: available at both build time and runtime
ENV APP_VERSION=${BUILD_VERSION}
ENV NODE_ENV=production \
PORT=3000
# Inside the container: echo $APP_VERSION
# Override at build time: docker build --build-arg BUILD_VERSION=2.0.0 .
# Override at run time: docker run -e NODE_ENV=development my-app
CMD and ENTRYPOINT
# CMD: default command when the container starts — can be overridden at docker run
CMD ["node", "server.js"]
CMD ["python", "-m", "gunicorn", "app:app"]
# ENTRYPOINT: fixed command — docker run args are only appended (replacing CMD)
# To override ENTRYPOINT you must use the flag: docker run --entrypoint <cmd>
ENTRYPOINT ["python"]
CMD ["app.py"]
# docker run my-image app.py → python app.py
# docker run my-image other_script.py → python other_script.py
# Shell form vs Exec form
CMD node server.js # shell form: /bin/sh -c "node server.js" — PID 1 is sh
CMD ["node", "server.js"] # exec form: node runs directly as PID 1 — RECOMMENDED
# PID 1 matters because it receives SIGTERM when the container stops
USER — Non-root
# Create a non-root user
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
USER appuser
# The official Node.js image already ships with a "node" user
USER node
# Note: USER only affects RUN/CMD/ENTRYPOINT that come after it.
# COPY/ADD ALWAYS create files owned by root — regardless of placement before or after USER.
# To make files owned by another user, use --chown:
COPY --chown=node:node . .
USER node
WORKDIR
# Create and switch to the working directory
WORKDIR /app
# All following COPY, RUN, CMD are relative to /app
COPY . . # copy into /app/
RUN ls # ls /app/
3. Layer caching — optimizing build time
Problem: dependencies get reinstalled constantly
# BAD: npm install reruns every time the code changes
WORKDIR /app
COPY . . # copy everything — code changes → cache miss
RUN npm ci # reruns every time!
Fix: copy package.json first
# GOOD: cache npm install separately from source code
WORKDIR /app
COPY package.json package-lock.json ./ # copy only the manifest
RUN npm ci --omit=dev # invalidated only when package.json changes
COPY . . # copy source — a cache miss only affects this layer
Rule: put rarely changing layers at the top (near FROM) and frequently changing layers at the bottom (near CMD).
4. Multi-stage build
Purpose
Reduce the production image size by separating the build stage (with compilers and tools) from the runtime stage (which only needs the binary/artifacts).
Example: Node.js app
Result: the runtime image does not contain the TypeScript compiler, .ts sources, or devDependencies.
Example: Go app (static binary)
FROM golang:1.22-alpine AS builder
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -o server .
# Tiny runtime image — contains only the binary
FROM scratch AS runtime
COPY --from=builder /app/server /server
EXPOSE 8080
ENTRYPOINT ["/server"]
# Image size: ~10 MB instead of ~800 MB
Example: Python app
FROM python:3.12-slim AS builder
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir --prefix=/install -r requirements.txt
FROM python:3.12-slim AS runtime
WORKDIR /app
COPY --from=builder /install /usr/local
COPY . .
RUN adduser --disabled-password --gecos '' appuser
USER appuser
EXPOSE 8000
CMD ["python", "-m", "gunicorn", "--bind", "0.0.0.0:8000", "app:app"]
5. .dockerignore
Like .gitignore — excludes files when the build context is sent to the daemon. It affects both build speed and security.
# .dockerignore
.git
.gitignore
node_modules # IMPORTANT: avoid copying node_modules from the host into the image
dist
build
*.log
.env # NEVER bake secrets into the image
.env.*
__pycache__
*.pyc
.pytest_cache
.coverage
Dockerfile*
docker-compose*.yml
README.md
Security note: Without
.dockerignoreyou can accidentally put.env, private keys, or.githistory into the image — then pushing it to ECR/Docker Hub leaks your secrets.
6. Best practices summary
Choosing a base image
# AVOID: image too large, many CVEs
FROM ubuntu:latest
FROM python:3.12
# BETTER: slim or alpine — smaller, fewer CVEs
FROM python:3.12-slim # Debian minimal (~130 MB instead of ~1 GB)
FROM node:24-alpine # Alpine Linux (~5 MB base, ~130 MB with Node)
FROM amazoncorretto:21-alpine # AWS Corretto JDK — optimized for EC2/Fargate
# SLIMMEST: distroless (Google) — only app + runtime, no shell
FROM gcr.io/distroless/python3
Image size comparison for Python
| Base image | Size |
|---|---|
python:3.12 | ~1 GB |
python:3.12-slim | ~130 MB |
python:3.12-alpine | ~55 MB |
gcr.io/distroless/python3 | ~50 MB |
Production Dockerfile checklist
[ ] Use a specific tag for the base image (not :latest)
[ ] .dockerignore exists and excludes .env and node_modules
[ ] Package manifest (package.json / requirements.txt) is COPY'd before source code
[ ] Multi-stage build if there is a compile/build step
[ ] Run as a non-root USER
[ ] Do not bake secrets (passwords, API keys) into the image
[ ] EXPOSE documents the correct port
[ ] CMD uses exec form ["node", "server.js"], not shell form
[ ] RUN apt/apk cleanup in the same layer as the install
Part 2: Docker Compose
1. Why Docker Compose?
Without Compose, running a 3-container app takes 3 long commands:
# Without Compose — complex, error-prone commands
docker network create myapp-net
docker run -d \
--name postgres \
--network myapp-net \
-e POSTGRES_PASSWORD=secret \
-v pgdata:/var/lib/postgresql/data \
postgres:16
docker run -d \
--name redis \
--network myapp-net \
redis:7-alpine
docker run -d \
--name web \
--network myapp-net \
-p 3000:3000 \
-e DATABASE_URL=postgres://postgres:secret@postgres:5432/mydb \
-e REDIS_URL=redis://redis:6379 \
myapp:latest
With Compose, everything lives in one file:
docker compose up -d
2. docker-compose.yml syntax
Overall structure
# docker-compose.yml
services: # Containers
web: # Service name
...
db:
...
volumes: # Named volumes
pgdata:
networks: # Custom networks (optional)
backend:
Version note: Compose V2 (built into Docker Desktop 2022+) uses
docker compose(no hyphen). Theversion:field at the top of the file is deprecated — omit it.
Detailed service definition
services:
web:
# 1. Image or build
image: nginx:1.27 # use an existing image
# or
build:
context: . # build context
dockerfile: Dockerfile # Dockerfile path
target: runtime # multi-stage target
# 2. Container name
container_name: my-web
# 3. Port mapping
ports:
- "8080:80" # host:container
- "443:443"
# 4. Environment variables
environment:
NODE_ENV: production
PORT: "3000"
# or from a file
env_file:
- .env
- .env.local
# 5. Volumes
volumes:
- ./src:/app/src # bind mount (dev — real-time code sync)
- uploads:/app/uploads # named volume (persist data)
- /tmp:/tmp:ro # read-only mount
# 6. Networks
networks:
- frontend
- backend
# 7. Dependency on another service
depends_on:
db:
condition: service_healthy # wait for the healthcheck to pass
# 8. Healthcheck
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
interval: 30s
timeout: 10s
retries: 3
start_period: 40s
# 9. Restart policy
restart: unless-stopped # always | on-failure | unless-stopped | no
# 10. Resource limits
deploy:
resources:
limits:
cpus: '0.5'
memory: 512M
3. Networking in Compose
Default network
Compose automatically creates a bridge network and attaches every service to it. Services talk to each other by service name (DNS resolution).
# The web service can connect to db using the hostname "db"
environment:
DATABASE_URL: "postgres://user:pass@db:5432/mydb"
# ^^
# Service name in Compose
Custom networks (separating frontend/backend)
services:
nginx:
networks: [frontend]
web:
networks: [frontend, backend]
db:
networks: [backend] # Not reachable from nginx
networks:
frontend:
backend:
internal: true # No internet access
4. Volumes — Persisting data
services:
db:
image: postgres:16
volumes:
- pgdata:/var/lib/postgresql/data # Named volume — persists across restart/recreate
web:
volumes:
- ./src:/app/src # Bind mount — sync code from the host (dev)
- uploads:/app/uploads # Named volume for user uploads
volumes:
pgdata: # Managed by Docker, stored in /var/lib/docker/volumes/
uploads:
Bind mount vs named volume:
| Criteria | Bind mount | Named volume |
|---|---|---|
| Path | Specific path on the host | Managed by Docker |
| Used for | Dev (syncing source code) | Production data (DB, uploads) |
| Ease of backup | Easy (you know the path) | Needs docker volume commands |
| Performance | Host filesystem | Better on Docker Desktop/Mac |
5. Full example: Web App + Postgres + Redis
Project structure
.env.example (committed to git)
# .env.example — copy to .env and fill in real values
POSTGRES_USER=myapp
POSTGRES_PASSWORD=changeme
POSTGRES_DB=myapp_db
REDIS_PASSWORD=changeme
APP_SECRET_KEY=changeme
docker-compose.yml (production-like)
docker-compose.override.yml (dev — do not commit)
# Overrides for the development environment
# Compose automatically merges this file with docker-compose.yml
services:
web:
build:
target: builder # use the builder stage (has devDependencies)
volumes:
- ./src:/app/src # real-time code sync (bind mount)
environment:
NODE_ENV: development
DEBUG: "true"
command: ["npm", "run", "dev"] # hot reload
db:
ports:
- "5432:5432" # expose the DB to the host for TablePlus/DBeaver
redis:
ports:
- "6379:6379"
6. Common Compose commands
# Start all services (detached)
docker compose up -d
# Start only some services
docker compose up -d db redis
# Rebuild images before starting
docker compose up -d --build
# View logs
docker compose logs -f
docker compose logs -f web # web service only
# View status
docker compose ps
# Exec into a service
docker compose exec web bash
docker compose exec db psql -U myapp -d myapp_db
# Stop (keep containers)
docker compose stop
# Stop and remove containers (keep volumes)
docker compose down
# Remove volumes too (DELETES DATA)
docker compose down -v
# Restart a service after changing code
docker compose restart web
# Scale a service
# Note: a service you want to scale must NOT set container_name (container names
# must be unique) and must not hard-code a host port — the full example in §5 sets
# container_name for the web service, so remove it before scaling
docker compose up -d --scale web=3
# One-off run (no restart)
docker compose run --rm web npm run migrate
7. Environment variables — precedence order
Highest → Lowest
1. docker compose run -e VAR=val (CLI flag)
2. Value interpolated from shell / .env (environment: VAR: ${VAR} — value
taken from the shell env or the .env file)
3. docker-compose.yml environment: (hard-coded inline value)
4. env_file: attribute (file declared in the compose file)
5. Dockerfile ENV instruction (lowest)
Note: a value hard-coded in
environment:(e.g.VAR: fixed) is NOT overridden by the shell environment — shell/.env only "wins" when the compose file interpolates (VAR: ${VAR}) or declaresVARwithout a value.
# Debug: view all env vars of a service
docker compose config # print the interpolated compose config
docker compose exec web env # print env vars inside the container
Review Questions
-
Why must
COPY package.json ./ && RUN npm cicome BEFORECOPY . .to take advantage of the cache?Show answer
Docker caches by layer: if one layer changes, every layer below it is invalidated. Source code changes often, but
package.jsonchanges much less. By copyingpackage.jsonfirst and runningnpm cias a separate layer, theRUN npm cilayer is only rebuilt whenpackage.jsonchanges — if you only edit code, the npm install layer stays cached, saving minutes of build time. -
What is the difference between the
CMDshell form and exec form with respect to PID 1?Show answer
The shell form
CMD node server.jsruns through/bin/sh -c, so PID 1 issh, notnode. When Docker sends SIGTERM (ondocker stop),shreceives the signal but does not forward it tonode→ the process does not shut down gracefully.The exec form
CMD ["node", "server.js"]runsnodedirectly as PID 1, so it receives SIGTERM correctly. Always use the exec form in production. -
How does a multi-stage build help the production image?
Show answer
A multi-stage build separates the build stage (with compilers, devDependencies, build tools) from the runtime stage (only the required artifacts). The final image contains no TypeScript compiler, test files,
.tssources, or devDependencies — significantly reducing size (e.g. from ~1 GB down to ~90 MB for a Node.js app) and shrinking the attack surface (fewer packages = fewer CVEs). -
Why MUST
.envbe in.dockerignore?Show answer
.envusually contains secrets (database passwords, API keys, tokens). If it is not in.dockerignore, the file is copied into the build context and can be baked into image layers. Anyone with that image (pulled from a registry) can extract the secrets viadocker historyordocker inspect..dockerignorekeeps this file out of the build context from the start — a security rule you cannot skip. -
When should you use
ADDinstead ofCOPY?Show answer
Use
ADDonly when you need one of its two special features: (1) automatically extracting a.tar.gzfile into the destination directory, or (2) copying from a URL (not recommended because it cannot be cached and carries security risk). In every other case — plain file/directory copies — useCOPYbecause it is clearer and more predictable. -
How do two services in the same Compose file communicate with each other (other than by IP)?
Show answer
By using the service name as the hostname. Compose creates a bridge network and registers DNS for each service. The
webservice can connect to thedbservice with hostnamedb(port 5432), or torediswith hostnameredis— no need to know dynamic IPs. -
What is the difference between a bind mount and a named volume?
Show answer
A bind mount maps a specific host path into the container — suitable for development (real-time source code sync). A named volume is managed by Docker under
/var/lib/docker/volumes/— suitable for production data (DB, uploads) because it persists acrossdocker compose downand performs better on Docker Desktop/Mac.A bind mount depends on the host directory layout; a named volume is more portable.
-
Which command stops and removes containers but keeps the data volumes?
Show answer
docker compose down(without the-vflag). It stops and removes the containers and the networks created by Compose, but keeps named volumes. Only adding-v(docker compose down -v) removes volumes — be careful, since that deletes your database data too. -
How does
docker compose up -d --builddiffer fromdocker compose up -d?Show answer
--buildforces Compose to rebuild the image from the Dockerfile before starting, even if the image already exists. Without--build, Compose uses the cached image (which may be an old version if the code has changed). Use--buildafter editing the Dockerfile or source code to make sure the container runs the latest code. -
Why should
.envnot be committed to git while.env.exampleshould?
Show answer
.env contains real secret values (passwords, API keys) — committing it means git history keeps those secrets forever, even if you delete the file later. .env.example contains the key template with placeholder values (no real secrets), so new developers know which variables to set without exposing sensitive information.
Hands-on Exercises
Part 1: Writing Dockerfiles
# 1. Create a simple Node.js application
mkdir myapp && cd myapp
cat > package.json << 'EOF'
{
"name": "myapp",
"version": "1.0.0",
"scripts": { "start": "node server.js" },
"dependencies": { "express": "^4.18.0" }
}
EOF
cat > server.js << 'EOF'
const express = require('express');
const app = express();
app.get('/', (req, res) => res.send('Hello Docker!'));
app.listen(3000, () => console.log('Server running on port 3000'));
EOF
# 2. Create .dockerignore
cat > .dockerignore << 'EOF'
node_modules
*.log
.env
EOF
# 3. Create the Dockerfile
cat > Dockerfile << 'EOF'
FROM node:24-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
USER node
EXPOSE 3000
CMD ["node", "server.js"]
EOF
# 4. Build and run
docker build -t myapp:1.0 .
docker run -d -p 3000:3000 --name myapp myapp:1.0
curl http://localhost:3000
# 5. View layers
docker history myapp:1.0
# 6. Add a multi-stage build
cat > Dockerfile.multistage << 'EOF'
FROM node:24-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .
FROM node:24-alpine AS runtime
WORKDIR /app
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/server.js ./
USER node
EXPOSE 3000
CMD ["node", "server.js"]
EOF
docker build -f Dockerfile.multistage -t myapp:multistage .
docker images myapp # compare sizes
# Clean up
docker rm -f myapp
docker rmi myapp:1.0 myapp:multistage
Part 2: Docker Compose
# Create the project directory
mkdir compose-demo && cd compose-demo
# Create the .env file
cat > .env << 'EOF'
POSTGRES_USER=demo
POSTGRES_PASSWORD=demopass
POSTGRES_DB=demodb
EOF
# Create docker-compose.yml
cat > docker-compose.yml << 'EOF'
services:
db:
image: postgres:16-alpine
environment:
POSTGRES_USER: ${POSTGRES_USER}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
POSTGRES_DB: ${POSTGRES_DB}
volumes:
- pgdata:/var/lib/postgresql/data
ports:
- "5432:5432"
healthcheck:
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER}"]
interval: 5s
retries: 5
redis:
image: redis:7-alpine
ports:
- "6379:6379"
volumes:
pgdata:
EOF
# Start up
docker compose up -d
# Check status
docker compose ps
# Connect to Postgres
docker compose exec db psql -U demo -d demodb -c "\l"
# View logs
docker compose logs db
# Clean up
docker compose down -v # -v removes the volume too
References
- Dockerfile reference
- Docker build best practices
- Multi-stage builds
- .dockerignore file
- Docker Compose overview
- Compose file reference
- Compose networking
- Compose secrets