Docker Cheat Sheet
Quick reference for Docker commands, Dockerfile best practices, Docker Compose patterns, and container debugging.
Deep dive: Docker Section | Docker Security
Container Lifecycle
| Command | Description |
|---|---|
docker run -d --name app img | Run container in background |
docker run -it img /bin/sh | Run container interactively |
docker run --rm img | Run and auto-remove on exit |
docker run -p 8080:3000 img | Map host port 8080 to container 3000 |
docker run -v /host:/cont img | Bind mount host directory |
docker run --env-file .env img | Load environment variables from file |
docker run -e KEY=val img | Set one environment variable |
docker run --network mynet img | Attach to a network |
docker run --restart unless-stopped img | Restart policy (no, on-failure[:N], always, unless-stopped) |
docker run --init img | Run a tiny init as PID 1 (forwards signals, reaps zombies) |
docker run -u 1000:1000 -w /app img | Run as user, set working dir |
docker run --platform linux/amd64 img | Run a specific architecture (emulated if needed) |
docker run --mount type=bind,src=.,dst=/app img | Explicit mount syntax (errors if src is missing) |
docker run --add-host host.docker.internal:host-gateway img | Reach the host from the container on Linux |
docker run --gpus all img | Expose GPUs (needs NVIDIA Container Toolkit) |
docker create img | Create without starting |
docker start container | Start a stopped container |
docker start -ai container | Start and attach interactively |
docker stop container | Graceful stop (SIGTERM, then SIGKILL after 10s; -t 30 to change) |
docker kill container | Immediate stop (SIGKILL) |
docker restart container | Stop and start |
docker rm container | Remove stopped container |
docker rm -f container | Force remove running container |
docker container prune | Remove all stopped containers |
docker rename old new | Rename a container |
docker update --memory 1g --restart always container | Change limits/restart policy of a running container |
docker wait container | Block until it exits, print exit code |
Image Management
| Command | Description |
|---|---|
docker build -t name:tag . | Build image from Dockerfile |
docker build -f Dockerfile.prod . | Build from specific Dockerfile |
docker build --no-cache . | Build without layer cache |
docker build --target build . | Stop at a named stage |
docker build --build-arg VERSION=1.2 . | Pass an ARG |
docker build --pull . | Always pull a newer base image |
docker build --progress=plain . | Full, uncollapsed build output |
docker images | List local images (docker image ls) |
docker image inspect img | Image metadata (env, entrypoint, layers) |
docker rmi img | Remove an image (docker image rm) |
docker image prune | Remove dangling images |
docker image prune -a | Remove all unused images |
docker tag img:v1 registry/img:v1 | Tag image for registry |
docker push registry/img:v1 | Push to registry |
docker pull img:tag | Pull from registry |
docker save img > img.tar | Export image to tarball (-o img.tar also works) |
docker load < img.tar | Import image from tarball (-i img.tar also works) |
docker history img | Show image layer history |
docker login ghcr.io | Log in to a registry (Docker Hub if omitted) |
docker logout | Log out |
docker init | Generate Dockerfile, compose.yaml and .dockerignore for the project in the current dir |
BuildKit & Buildx
BuildKit is the default builder. docker buildx exposes all of its features.
| Command | Description |
|---|---|
docker buildx ls | List builders and the platforms they support |
docker buildx create --name multi --use | Create a builder that can do multi-platform builds |
docker buildx build --platform linux/amd64,linux/arm64 -t reg/img:1.0 --push . | Multi-arch build, push the manifest list |
docker buildx build --load -t img . | Build and load the result into local images |
docker buildx build --cache-to type=registry,ref=reg/img:cache,mode=max --cache-from type=registry,ref=reg/img:cache . | Share cache via a registry |
docker buildx build --cache-to type=gha,mode=max --cache-from type=gha . | Cache in GitHub Actions |
docker buildx build --secret id=npmrc,src=$HOME/.npmrc . | Pass a secret without baking it into a layer |
docker buildx build --ssh default . | Forward your SSH agent (private git deps) |
docker buildx build -o type=local,dest=out . | Export build output files instead of an image |
docker buildx imagetools inspect img | Show a remote image's manifest list (platforms) |
docker buildx bake | Build targets defined in docker-bake.hcl / compose file |
docker builder prune | Clear build cache |
Container Inspection
| Command | Description |
|---|---|
docker ps | List running containers |
docker ps -a | List all containers |
docker logs container | View container logs |
docker logs -f container | Follow container logs |
docker logs --tail 100 container | Last 100 log lines |
docker logs --since 10m -t container | Logs from the last 10 minutes, with timestamps |
docker inspect container | Full container JSON metadata |
docker inspect -f '<go-template>' container | Extract one field (examples under Debugging) |
docker events | Stream daemon events (start, die, oom...) |
docker stats | Live resource usage |
docker top container | Running processes in container |
docker diff container | Filesystem changes since start |
docker port container | Port mappings |
Exec & Copy
| Command | Description |
|---|---|
docker exec -it container sh | Shell into running container |
docker exec container cmd | Run command in container |
docker exec -u root -it container sh | Shell as root |
docker exec -e DEBUG=1 container cmd | Run with an extra env var |
docker debug container | Debug shell with tools, even for distroless/scratch images (Docker Desktop) |
docker cp container:/path ./local | Copy from container to host |
docker cp ./local container:/path | Copy from host to container |
Dockerfile Patterns
Production Node.js Dockerfile
# syntax=docker/dockerfile:1
# Stage 1: Install dependencies
FROM node:26-alpine AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN --mount=type=cache,target=/root/.npm npm ci --omit=dev
# Stage 2: Build
FROM node:26-alpine AS build
WORKDIR /app
COPY package.json package-lock.json ./
RUN --mount=type=cache,target=/root/.npm npm ci
COPY . .
RUN npm run build
# Stage 3: Production
FROM node:26-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production
RUN addgroup -g 1001 -S app && \
adduser -S -u 1001 -G app app
COPY --from=deps /app/node_modules ./node_modules
COPY --from=build /app/dist ./dist
COPY package.json ./
USER app
EXPOSE 3000
CMD ["node", "dist/main.js"]
Production Go Dockerfile
FROM golang:1.27-alpine AS build
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o /server ./cmd/server
FROM scratch
COPY --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
COPY --from=build /server /server
USER 65534:65534
EXPOSE 8080
ENTRYPOINT ["/server"]
gcr.io/distroless/static-debian12:nonroot is an alternative to scratch that already has CA certs, /etc/passwd and tzdata.
Multi-Stage Build Tricks
| Pattern | Example |
|---|---|
| Name a stage | FROM node:26-alpine AS build |
| Copy from a stage | COPY --from=build /app/dist ./dist |
| Copy from any image | COPY --from=nginx:alpine /etc/nginx/nginx.conf . |
| Build only up to a stage | docker build --target build . |
| Base a stage on another stage | FROM build AS test |
| Cross-compile without emulation | FROM --platform=$BUILDPLATFORM golang:1.27 AS build then ARG TARGETOS TARGETARCH and GOOS=$TARGETOS GOARCH=$TARGETARCH go build |
BuildKit Dockerfile Features
# syntax=docker/dockerfile:1
# Cache package manager downloads across builds
RUN --mount=type=cache,target=/root/.cache/go-build go build ./...
# Use a secret at build time without leaving it in a layer
RUN --mount=type=secret,id=npmrc,target=/root/.npmrc npm ci
# Use the SSH agent for private git repos (build with --ssh default)
RUN --mount=type=ssh git clone git@github.com:org/private.git
# Bind-mount files from the context without copying them into a layer
RUN --mount=type=bind,source=package.json,target=package.json npm ci
# Heredocs
RUN <<EOF
apt-get update
apt-get install -y --no-install-recommends curl
rm -rf /var/lib/apt/lists/*
EOF
# Set owner/permissions while copying (no extra chown layer)
COPY --chown=app:app --chmod=755 entrypoint.sh /usr/local/bin/
Key Dockerfile Instructions
| Instruction | Purpose | Example |
|---|---|---|
FROM | Base image | FROM node:26-alpine |
WORKDIR | Set working directory | WORKDIR /app |
COPY | Copy files (respects .dockerignore) | COPY . . |
ADD | Copy + extract archives + URLs | ADD app.tar.gz /app |
RUN | Execute command during build | RUN npm ci |
CMD | Default command (overridable) | CMD ["node", "app.js"] |
ENTRYPOINT | Fixed command (args appended) | ENTRYPOINT ["/server"] |
ENV | Set environment variable | ENV NODE_ENV=production |
ARG | Build-time variable | ARG VERSION=latest |
EXPOSE | Document port (does not publish) | EXPOSE 3000 |
VOLUME | Create mount point | VOLUME /data |
USER | Set runtime user | USER app |
HEALTHCHECK | Container health check | See below |
LABEL | Image metadata | LABEL org.opencontainers.image.source=https://github.com/org/repo |
SHELL | Change shell for shell-form commands | SHELL ["/bin/bash", "-o", "pipefail", "-c"] |
STOPSIGNAL | Signal sent by docker stop | STOPSIGNAL SIGQUIT |
ARG before the first FROM is only visible to FROM lines; redeclare it (ARG VERSION) inside a stage to use it there. ENV persists into the running container, ARG does not.
Healthcheck
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD wget --no-verbose --tries=1 --spider http://localhost:3000/health || exit 1
Layer Optimization
Order matters -- put rarely-changing layers first:
# 1. System deps (rarely change)
RUN apk add --no-cache curl
# 2. App deps (change sometimes)
COPY package.json package-lock.json ./
RUN npm ci
# 3. App code (changes often)
COPY . .
RUN npm run build
Reduce layers -- combine related RUN commands:
# Bad: 3 layers
RUN apt-get update
RUN apt-get install -y curl
RUN rm -rf /var/lib/apt/lists/*
# Good: 1 layer
RUN apt-get update && \
apt-get install -y curl && \
rm -rf /var/lib/apt/lists/*
Docker Compose
Full reference: Docker Compose Cheat Sheet.
Basic Compose File
services:
app:
build: .
ports:
- "3000:3000"
environment:
- DATABASE_URL=postgres://user:pass@db:5432/mydb
- REDIS_URL=redis://cache:6379
depends_on:
db:
condition: service_healthy
cache:
condition: service_started
volumes:
- .:/app
- /app/node_modules
db:
image: postgres:18-alpine
environment:
POSTGRES_USER: user
POSTGRES_PASSWORD: pass
POSTGRES_DB: mydb
volumes:
- pgdata:/var/lib/postgresql # postgres 18+ images; use /var/lib/postgresql/data for 17 and older
healthcheck:
test: ["CMD-SHELL", "pg_isready -U user"]
interval: 5s
timeout: 5s
retries: 5
cache:
image: redis:8-alpine
ports:
- "6379:6379"
volumes:
pgdata:
Compose Commands
| Command | Description |
|---|---|
docker compose up | Start all services |
docker compose up -d | Start in background |
docker compose up --build | Rebuild and start |
docker compose down | Stop and remove |
docker compose down -v | Stop, remove, and delete volumes |
docker compose logs -f app | Follow logs for one service |
docker compose exec app sh | Shell into service |
docker compose ps | List service status |
docker compose restart app | Restart one service |
docker compose pull | Pull latest images |
docker compose config | Validate and view merged config |
docker compose watch | Sync/rebuild on file changes (needs develop.watch) |
docker compose run --rm app npm test | One-off command in a new container |
Networking
| Command | Description |
|---|---|
docker network ls | List networks |
docker network create mynet | Create network |
docker network inspect mynet | Inspect network details |
docker network connect mynet container | Connect container to network |
docker network disconnect mynet container | Disconnect from network |
Network Types
| Type | Use Case |
|---|---|
bridge | Default. Single host. Containers resolve each other by name only on a user-defined bridge (docker network create); the built-in bridge network has no DNS |
host | Container shares host network. No port mapping needed (Linux; opt-in on Docker Desktop) |
none | No networking. Complete isolation |
overlay | Multi-host networking (Swarm) |
macvlan / ipvlan | Container gets its own address on the physical LAN |
-p 8080:3000 binds on all host interfaces (0.0.0.0) and bypasses ufw/firewalld rules. Use -p 127.0.0.1:8080:3000 for local-only.
Volumes
| Command | Description |
|---|---|
docker volume ls | List volumes |
docker volume create myvol | Create named volume |
docker volume inspect myvol | Volume details |
docker volume rm myvol | Delete volume |
docker volume prune | Remove unused anonymous volumes |
docker volume prune -a | Remove all unused volumes, named ones too |
Back up a named volume:
docker run --rm -v myvol:/data -v "$PWD":/backup alpine tar czf /backup/myvol.tgz -C /data .
Volume Types
# Named volume (Docker manages storage)
docker run -v myvol:/data img
# Bind mount (host path)
docker run -v /host/path:/container/path img
# tmpfs mount (in-memory, Linux only)
docker run --tmpfs /tmp img
# Read-only mount
docker run -v /host/path:/data:ro img
Debugging Containers
Container Will Not Start
# Check logs
docker logs container
# Inspect exit code (137 = SIGKILL, often OOM; 143 = SIGTERM)
docker inspect container --format='Exit: {{.State.ExitCode}} OOMKilled: {{.State.OOMKilled}}'
# Run interactively to debug
docker run -it --entrypoint sh img
# Check resource limits
docker stats container
Container Is Slow
# Check resource usage
docker stats container
# Check process list
docker top container
# Profile with strace (if available)
docker exec container strace -p 1 -c
Networking Issues
# Check container IP
docker inspect container | grep '"IPAddress"'
docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}} {{end}}' container
# Debug with a full network toolbox in the container's network namespace
docker run --rm -it --network container:<name> nicolaka/netshoot
# Test DNS resolution
docker exec container nslookup other-service
# Test connectivity
docker exec container wget -qO- http://other-service:3000/health
# Check port bindings
docker port container
Disk Space Issues
# Check Docker disk usage
docker system df
# Detailed breakdown
docker system df -v
# Clean everything unused
docker system prune -a --volumes
# Build cache is often the biggest item
docker builder prune --keep-storage 10GB
Contexts (Remote Daemons)
| Command | Description |
|---|---|
docker context ls | List contexts |
docker context create prod --docker host=ssh://user@host | Daemon over SSH |
docker context use prod | Switch default context |
docker --context prod ps | Use a context for one command |
DOCKER_HOST=ssh://user@host docker ps | Same, via env var |
Security Quick Reference
| Practice | Command / Pattern |
|---|---|
| Run as non-root | USER 1001 in Dockerfile |
| Read-only filesystem | docker run --read-only img |
| Drop capabilities | docker run --cap-drop ALL img |
| No new privileges | docker run --security-opt no-new-privileges img |
| Resource limits | docker run -m 512m --cpus 1 img |
| Scan for vulnerabilities | docker scout cves img (docker scout quickview img for a summary) |
| Build-time secrets | RUN --mount=type=secret,id=..., never ARG/ENV |
| Use minimal base image | FROM alpine or FROM scratch |
| Pin image digests | FROM node@sha256:abc123... |
When to Use X vs Y
| Decision | Choice A | Choice B | Use A When | Use B When |
|---|---|---|---|---|
| Base image | alpine | debian-slim | Size matters, no glibc deps | Need glibc, broad package support |
| Base image | node:alpine | scratch | Need runtime (Node, Python) | Compiled binary (Go, Rust) |
| Mount type | Named volume | Bind mount | Persistent data (DB, uploads) | Development hot-reload |
| CMD format | Exec form ["cmd"] | Shell form cmd | Production (signal handling) | Need shell expansion |
| Multi-stage | Yes | No | Production images | Simple dev Dockerfiles |
| Compose | Yes | No | Multi-container local dev | Single container, CI/CD |
.dockerignore Template
node_modules
.git
.gitignore
.env*
*.md
dist
coverage
.vscode
.idea
docker-compose*.yml
Dockerfile*
.dockerignore
Test Yourself
-
What flag auto-removes a container when it exits?
docker run --rm -
How do you map host port 8080 to container port 3000?
docker run -p 8080:3000 img -
What command shows live resource usage of running containers?
docker stats -
How do you build an image without using the layer cache?
docker build --no-cache . -
What command gets a shell into an already-running container?
docker exec -it container sh -
What Dockerfile instruction sets the default command that can be overridden at runtime?
CMD -
How do you stop and remove all containers, networks, and volumes created by Compose?
docker compose down -v -
What command scans an image for known vulnerabilities?
docker scout cves img -
How do you copy a file from a container to the host?
docker cp container:/path ./local -
What is the purpose of
EXPOSEin a Dockerfile? It documents the port the container listens on but does NOT actually publish it.
Common Gotchas
- Running as root inside containers. Always add a
USERinstruction in production Dockerfiles -- running as root means a container escape grants root on the host. - Using
latesttag in production. Thelatesttag is mutable and can change without warning. Pin image versions or use digests (node@sha256:...). - Forgetting
.dockerignore. Without it,COPY . .sends your entire directory (includingnode_modules,.git,.env) to the build context, bloating images and leaking secrets. - Putting
COPY . .beforeRUN npm install. This busts the dependency cache on every code change. Copypackage.jsonand lock file first, install, then copy the rest. - Shell-form
CMD/ENTRYPOINTswallow signals.CMD node app.jsruns under/bin/sh -c, so SIGTERM never reaches node anddocker stopwaits 10s then kills. Use exec form["node", "app.js"], and--initortiniif your process does not reap children. - Secrets in
ARG/ENVend up in the image. They are visible indocker historyanddocker inspect. Use BuildKit secret mounts. apt-get updatein its ownRUNlayer goes stale. The cached layer is reused while the install line changes. Alwaysapt-get update && apt-get installin oneRUN.- Published ports skip the host firewall. Docker writes its own iptables rules, so ufw does not block
-p 5432:5432. Bind to127.0.0.1for local-only services. - Images built on Apple Silicon are arm64. They fail with
exec format erroron amd64 servers. Build with--platform linux/amd64or multi-arch via buildx.
One-Liner Summary
Docker packages your app and its dependencies into an isolated, portable container that runs the same everywhere -- master the Dockerfile layer cache and multi-stage builds to keep images small and builds fast.