Commands
docker build -t app:1.0 .
docker run -d --name app -p 8080:3000 -e NODE_ENV=prod app:1.0
docker ps -a; docker logs -f app; docker exec -it app sh
docker stop app && docker rm app
docker images; docker rmi app:1.0; docker system prune -af
docker inspect app; docker stats
docker tag app:1.0 123.dkr.ecr.us-east-1.amazonaws.com/app:1.0
docker push 123.dkr.ecr.us-east-1.amazonaws.com/app:1.0
docker buildx build --platform linux/amd64,linux/arm64 -t app --push .Multi-stage Dockerfile (Node)
FROM node:22-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build && npm prune --omit=dev
FROM node:22-alpine
WORKDIR /app
ENV NODE_ENV=production
COPY --from=build /app/node_modules ./node_modules
COPY --from=build /app/dist ./dist
USER node
EXPOSE 3000
HEALTHCHECK CMD wget -qO- http://localhost:3000/health || exit 1
CMD ["node", "dist/server.js"]Go: tiny image
FROM golang:1.23 AS build
WORKDIR /src
COPY go.* ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -ldflags="-s -w" -o /app
FROM gcr.io/distroless/static
COPY --from=build /app /app
ENTRYPOINT ["/app"]Instructions
| Instruction | Note |
|---|---|
FROM | base image; pin versions/digests |
RUN | runs at build time, creates a layer |
COPY vs ADD | prefer COPY; ADD also untars/fetches URLs |
CMD | default args, overridable |
ENTRYPOINT | fixed executable; CMD supplies its args |
ARG vs ENV | build-time only vs runtime env |
EXPOSE | documentation only |
Use exec form ["node", "app.js"] so the process is PID 1 and receives SIGTERM.
Layer caching
- Order from least to most frequently changing: deps manifest → install → source.
- Any changed layer invalidates all layers after it.
.dockerignore:node_modules,.git,dist,.env.- BuildKit cache mounts:
RUN --mount=type=cache,target=/root/.npm npm ci.
Compose
services:
api:
build: .
ports: ["3000:3000"]
environment: { DATABASE_URL: postgres://app:pw@db:5432/app }
depends_on: { db: { condition: service_healthy } }
db:
image: postgres:16
environment: { POSTGRES_PASSWORD: pw, POSTGRES_USER: app }
volumes: [pgdata:/var/lib/postgresql/data]
healthcheck: { test: ["CMD", "pg_isready", "-U", "app"], interval: 5s }
volumes: { pgdata: {} }docker compose up -d --build; docker compose logs -f api; docker compose down -vConcepts
- Container vs VM: containers share the host kernel (namespaces + cgroups); VMs virtualize hardware with their own kernel.
- Namespaces isolate (pid, net, mnt, uts, ipc, user); cgroups limit CPU/memory.
- Image = read-only layers; container = image + writable layer.
- Volumes (managed, persistent) vs bind mounts (host path) vs tmpfs.
- Networks: bridge (default), host, none, overlay (multi-host).
Security
- Run as non-root (
USER), read-only root FS where possible. - Minimal bases: alpine, distroless, scratch. Fewer packages, fewer CVEs.
- Scan images (Trivy, ECR scanning); pin by digest; sign (cosign).
- Never bake secrets into images or build args; inject at runtime.