devHọc Dev

Week 1 - Day 2: Writing Dockerfiles and Docker Compose

Week 1 – Day 2

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.yml syntax (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).

┌──────────────────────────────────────────────┐│FROMnode:24-alpine(rarelychanges)│←cachedthelongest│RUNapt-getinstall...(rarelychanges)││COPYpackage.json(seldomchanges)││RUNnpmci(seldomchanges)││COPY..(oftenchanges)│←frequentcachemisses│CMD["node","server.js"]│└──────────────────────────────────────────────┘

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

#───Stage1:Builder─────────────────────────────────────────FROMnode:24-alpineASbuilderWORKDIR/appCOPYpackage*.json./RUNnpmci#installsdevDependenciestooCOPY..RUNnpmrunbuild#compileTypeScript,bundle,etc.RUNnpmprune--omit=dev#dropdevDependenciesfromnode_modules#───Stage2:Runtime─────────────────────────────────────────FROMnode:24-alpineASruntimeWORKDIR/app#CopyonlywhatisneededfrombuilderCOPY--from=builder/app/dist./distCOPY--from=builder/app/node_modules./node_modulesCOPYpackage.json./#Security:non-rootuserUSERnodeEXPOSE3000CMD["node","dist/server.js"]

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 .dockerignore you can accidentally put .env, private keys, or .git history 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 imageSize
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). The version: 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).

┌──────────────────────────────────────────────────┐│myapp_defaultnetwork││┌─────────┐┌─────────┐┌─────────────┐│││web││db││redis││││:3000││:5432││:6379│││└────┬────┘└────┬────┘└──────┬──────┘│││││││service"web"cancall:│││db:5432(TCP)───────────────────▶│││redis:6379(TCP)─────────────────▶││└──────────────────────────────────────────────────┘
# 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:

CriteriaBind mountNamed volume
PathSpecific path on the hostManaged by Docker
Used forDev (syncing source code)Production data (DB, uploads)
Ease of backupEasy (you know the path)Needs docker volume commands
PerformanceHost filesystemBetter on Docker Desktop/Mac

5. Full example: Web App + Postgres + Redis

Project structure

myproject/├──docker-compose.yml├──docker-compose.override.yml#devoverrides├──.env#localsecrets(donotcommit)├──.env.example#template(commit)├──Dockerfile├──src/│└──app.js└──nginx/└──nginx.conf

.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)

services:#───PostgreSQL──────────────────────────────────────────────db:image:postgres:16-alpinecontainer_name:myapp_dbrestart:unless-stoppedenvironment:POSTGRES_USER:${POSTGRES_USER}POSTGRES_PASSWORD:${POSTGRES_PASSWORD}POSTGRES_DB:${POSTGRES_DB}volumes:-pgdata:/var/lib/postgresql/datahealthcheck:test:["CMD-SHELL","pg_isready-U${POSTGRES_USER}-d${POSTGRES_DB}"]interval:10stimeout:5sretries:5networks:-backend#───Redis───────────────────────────────────────────────────redis:image:redis:7-alpinecontainer_name:myapp_redisrestart:unless-stoppedcommand:redis-server--requirepass${REDIS_PASSWORD}volumes:-redisdata:/datahealthcheck:test:["CMD","redis-cli","-a","${REDIS_PASSWORD}","ping"]interval:10stimeout:5sretries:5networks:-backend#───WebApp─────────────────────────────────────────────────web:build:context:.dockerfile:Dockerfiletarget:runtimecontainer_name:myapp_webrestart:unless-stoppedenvironment:NODE_ENV:productionDATABASE_URL:"postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}"REDIS_URL:"redis://:${REDIS_PASSWORD}@redis:6379"SECRET_KEY:${APP_SECRET_KEY}depends_on:db:condition:service_healthyredis:condition:service_healthynetworks:-frontend-backend#───Nginxreverseproxy─────────────────────────────────────nginx:image:nginx:1.27-alpinecontainer_name:myapp_nginxrestart:unless-stoppedports:-"80:80"volumes:-./nginx/nginx.conf:/etc/nginx/conf.d/default.conf:rodepends_on:-webnetworks:-frontendvolumes:pgdata:redisdata:networks:frontend:backend:internal:true

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 declares VAR without 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

  1. Why must COPY package.json ./ && RUN npm ci come BEFORE COPY . . 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.json changes much less. By copying package.json first and running npm ci as a separate layer, the RUN npm ci layer is only rebuilt when package.json changes — if you only edit code, the npm install layer stays cached, saving minutes of build time.

  2. What is the difference between the CMD shell form and exec form with respect to PID 1?

    Show answer

    The shell form CMD node server.js runs through /bin/sh -c, so PID 1 is sh, not node. When Docker sends SIGTERM (on docker stop), sh receives the signal but does not forward it to node → the process does not shut down gracefully.

    The exec form CMD ["node", "server.js"] runs node directly as PID 1, so it receives SIGTERM correctly. Always use the exec form in production.

  3. 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, .ts sources, 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).

  4. Why MUST .env be in .dockerignore?

    Show answer

    .env usually 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 via docker history or docker inspect. .dockerignore keeps this file out of the build context from the start — a security rule you cannot skip.

  5. When should you use ADD instead of COPY?

    Show answer

    Use ADD only when you need one of its two special features: (1) automatically extracting a .tar.gz file 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 — use COPY because it is clearer and more predictable.

  6. 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 web service can connect to the db service with hostname db (port 5432), or to redis with hostname redis — no need to know dynamic IPs.

  7. 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 across docker compose down and performs better on Docker Desktop/Mac.

    A bind mount depends on the host directory layout; a named volume is more portable.

  8. Which command stops and removes containers but keeps the data volumes?

    Show answer

    docker compose down (without the -v flag). 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.

  9. How does docker compose up -d --build differ from docker compose up -d?

    Show answer

    --build forces 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 --build after editing the Dockerfile or source code to make sure the container runs the latest code.

  10. Why should .env not be committed to git while .env.example should?

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


Next lesson →