iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Docker Exercises

Three short Docker exercises to lock in builds, networks, and compose.

Three short challenges

EXAMPLE
# 1. Multi-stage Node API in under 200MB
# Goal: produce an image that runs a hello-world Express app
# and ends up under 200MB on disk.

# Dockerfile
FROM node:20-alpine AS deps
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev

FROM node:20-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

FROM gcr.io/distroless/nodejs20-debian12
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY --from=build /app/dist ./dist
USER nonroot
EXPOSE 3000
CMD ['dist/server.js']

# Build and check
# docker build -t hello .
# docker image inspect hello --format '{{.Size}}'


# 2. Compose with API + Postgres + healthchecks
# docker-compose.yml
services:
  db:
    image: postgres:16
    environment:
      POSTGRES_USER: app
      POSTGRES_PASSWORD: dev
      POSTGRES_DB: app
    healthcheck:
      test: ['CMD-SHELL', 'pg_isready -U app']
      interval: 5s
      retries: 10
    volumes:
      - pgdata:/var/lib/postgresql/data

  api:
    build: .
    environment:
      DATABASE_URL: postgres://app:dev@db:5432/app
    depends_on:
      db:
        condition: service_healthy
    ports:
      - '3000:3000'

volumes:
  pgdata:

# docker compose up -d
# docker compose logs -f api


# 3. BuildKit cache mount + multi-platform
# Dockerfile (with syntax line)
# syntax=docker/dockerfile:1.7
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN --mount=type=cache,target=/root/.npm npm ci
COPY . .
RUN npm run build

# Build for both architectures
# docker buildx create --use   # one-time
# docker buildx build --platform linux/amd64,linux/arm64 -t me/app:1 --push .


# Stretch
# - Add a HEALTHCHECK to the API Dockerfile
# - Run rootless: append USER node before CMD
# - Use docker scout cves hello to scan the image for vulnerabilities

Why it matters

These three cover the daily Docker surface area: small images, compose for local dev, BuildKit for cache + multi-arch. After this, the next level is image signing and OCI registry workflows.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
# Fill in the blank.
docker run -d ____ 8080:3000 my-api
Try it Yourself »

Discussion

Loading…