| |

Docker 101 🐳 Cheatsheet

⏱️ Estimated read: 6 min | |

A quick-reference for Docker commands, concepts, and internals. Organized for lookup, not for reading.


Container Lifecycle

CommandPurpose
docker run <image>Create + start container
docker run -d <image>Detached (background)
docker run -it <image> shInteractive with TTY
docker run --rm <image>Auto-remove on exit
docker run --name foo <image>Named container
docker start <c>Start stopped container
docker stop <c>Graceful stop (SIGTERM, then SIGKILL after 10s)
docker kill <c>Immediate SIGKILL
docker restart <c>Stop + start
docker pause <c>Freeze processes (cgroup freezer)
docker unpause <c>Resume
docker rm <c>Remove container
docker rm -f <c>Force remove (running)
docker psRunning containers
docker ps -aAll containers
docker logs <c>Container logs
docker logs -f <c>Follow logs

Images

CommandPurpose
docker pull <image>Pull from registry
docker push <image>Push to registry
docker imagesList local images
docker rmi <image>Remove image
docker build -t name:tag .Build from Dockerfile
docker build --no-cache -t name .Build without cache
docker tag src dstTag image
docker save -o img.tar <image>Export to tar
docker load -i img.tarImport from tar
docker history <image>Layer history
docker inspect <image>Full metadata JSON
docker image pruneRemove dangling images
docker image prune -aRemove all unused

Dockerfile Instructions

InstructionPurpose
FROM <image>Base image
WORKDIR /pathSet working directory
COPY src dstCopy from build context
COPY --from=<stage> src dstCopy from build stage
ADD src dstCopy + extract archives + URL
RUN cmdExecute during build
CMD ["exe","arg"]Default command (overridable)
ENTRYPOINT ["exe"]Fixed entrypoint
ENV KEY=valEnvironment variable
ARG NAMEBuild-time variable
EXPOSE 8080Document port (no publish)
USER appRun as user
VOLUME /dataDeclare volume
HEALTHCHECK CMD ...Health check
LABEL k=vMetadata
SHELL ["/bin/bash","-c"]Change shell
ONBUILD cmdTrigger in child images
STOPSIGNAL SIGTERMCustom stop signal

Ports & Networking

FlagPurpose
-p 8080:80Host:container port
-p 127.0.0.1:8080:80Bind to specific host IP
-PPublish all EXPOSE ports (random host)
--network bridgeDefault bridge
--network hostHost network (no isolation)
--network noneNo networking
--network mynetUser-defined network
--hostname fooContainer hostname
--dns 8.8.8.8Custom DNS
--add-host h:ip/etc/hosts entry
Network commandPurpose
docker network lsList networks
docker network create mynetCreate bridge network
docker network inspect mynetShow details
docker network connect mynet <c>Attach container
docker network disconnect mynet <c>Detach
docker network rm mynetRemove

Volumes & Storage

CommandPurpose
docker volume create volCreate volume
docker volume lsList volumes
docker volume inspect volShow details
docker volume rm volRemove
docker volume pruneRemove unused
FlagPurpose
-v vol:/dataNamed volume
-v /host:/dataBind mount
-v /host:/data:roRead-only bind
--mount type=bind,src=/h,dst=/dExplicit mount
--tmpfs /tmpTemporary filesystem
--read-onlyRead-only rootfs

Resources & Limits

FlagPurpose
--memory 512mMemory limit
--memory-swap 1gMemory + swap limit
--cpus 1.5CPU limit (1.5 cores)
--cpuset-cpus 0,1Pin to specific CPUs
--pids-limit 100Process limit
--ulimit nofile=1024:1024FD limit
--blkio-weight 500Block I/O weight
--device-read-bps /dev/sda:1mbRead bandwidth limit

Security

FlagPurpose
--user 1000:1000Run as UID:GID
--read-onlyImmutable rootfs
--cap-drop ALLDrop all capabilities
--cap-add NET_BIND_SERVICEAdd back specific caps
--security-opt no-new-privilegesPrevent escalation
--security-opt seccomp=profile.jsonCustom seccomp
--privilegedFull host access — avoid
--userns-remapUser namespace remapping
Common capabilitiesPurpose
NET_BIND_SERVICEBind ports < 1024
NET_ADMINNetwork configuration
SYS_ADMINMount, namespace ops (dangerous)
SYS_PTRACEDebug/strace
CHOWNChange file ownership

Compose

CommandPurpose
docker compose up -dStart stack, detached
docker compose downStop + remove containers
docker compose down -vAlso remove volumes
docker compose psList services
docker compose logs -f svcFollow service logs
docker compose exec svc shShell into service
docker compose buildBuild images
docker compose restart svcRestart service
docker compose pullPull images
services:
  app:
    image: myapp:1.0
    ports: ["8080:80"]
    environment:
      - KEY=val
    depends_on: [db]
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost/health"]
      interval: 10s
      retries: 3
  db:
    image: postgres:16
    volumes: [pgdata:/var/lib/postgresql/data]
    environment:
      POSTGRES_PASSWORD: secret
volumes:
  pgdata:

Inspection & Debugging

CommandPurpose
docker inspect <c>Full JSON metadata
docker inspect -f '{{.State.Pid}}' <c>Extract a field
docker statsLive resource usage
docker top <c>Processes in container
docker diff <c>Filesystem changes
docker port <c>Port mappings
docker cp <c>:/path .Copy from container
docker cp . <c>:/pathCopy to container
docker eventsReal-time daemon events
docker system dfDisk usage
docker system prune -aRemove all unused

Networking Internals

Packet path: host → container

Physical NIC → Netfilter PREROUTING (DNAT) → docker0 bridge → veth → container eth0 → app

Key constructs

ConstructPurpose
docker0Default bridge
br-<id>User-defined bridge
veth pairVirtual cable (host ↔ container)
Netfilter DNATRewrites host:port → container:port
conntrackReverses NAT on return path
docker-proxyUserspace fallback for loopback/hairpin

Finding the veth

PID=$(docker inspect -f '{{.State.Pid}}' mycontainer)
IFLINK=$(nsenter -t $PID -n -- cat /sys/class/net/eth0/iflink)
ip -o link | awk -F': ' -v iflink=$IFLINK '$1==iflink{print $2}'

Capture inside container

nsenter -t $PID -n -- tcpdump -nn -i eth0 port 80

Storage Driver

DriverCharacteristics
overlay2Default, good performance
btrfsSnapshots, needs btrfs
zfsSnapshots, needs zfs
vfsDeep copy, slow, testing only
CommandPurpose
docker info | grep "Storage Driver"Check driver
docker system df -vPer-image/volume usage

Image Build Patterns

PatternDockerfile
Multi-stageFROM build AS b … FROM scratch
ScratchFROM scratch + static binary
DistrolessFROM gcr.io/distroless/static
Build cacheCOPY pubspec.* . before COPY . .
Non-rootRUN useradd app + USER app

Multi-stage example

FROM golang:1.22 AS build
WORKDIR /app
COPY . .
RUN CGO_ENABLED=0 go build -o /app/server

FROM scratch
COPY --from=build /app/server /server
ENTRYPOINT ["/server"]

Health Checks

HEALTHCHECK --interval=30s --timeout=5s --retries=3 \
  CMD curl -f http://localhost:8080/health || exit 1
FieldDefault
interval30s
timeout30s
retries3
start_period0s
StateMeaning
startingWithin start_period
healthyCheck passing
unhealthyCheck failing after retries

Zero-Downtime Deploy

Swarm rolling

docker service update \
  --image myapp:v2 \
  --update-order start-first \
  --update-failure-action rollback \
  myapp

Blue-green switch

# 1. Deploy new color
docker compose up -d app-green
# 2. Health check directly
curl -sf http://app-green:8080/health
# 3. Swap upstream + reload
echo "upstream app_active { server app-green:8080; }" > nginx/active.conf
docker compose exec nginx nginx -s reload

Common Flags Cheatsheet

FlagMeaning
-dDetached
-itInteractive + TTY
--rmRemove on exit
--nameContainer name
-e KEY=valEnvironment var
--env-file .envEnv from file
-v src:dstVolume/bind mount
-p host:contPort mapping
-w /pathWorking directory
-u userUser
--entrypointOverride entrypoint
--restart unless-stoppedRestart policy

Gotchas

TrapReality
EXPOSE publishes portNo; only documents. Use -p
CMD is fixedOverridable; ENTRYPOINT is not (without --entrypoint)
Container IP is stableNo; changes on restart
docker stop is instantSends SIGTERM, waits 10s, then SIGKILL
--privileged = rootWorse; full host capabilities
Container writes persistOnly in writable layer or volumes; lost on rm
COPY . . is cachedCached until any file changes
latest tag pulls alwaysPulled on docker pull, not on docker run
docker ps shows stoppedNo; use -a
Bridge DNSOnly user-defined bridges have embedded DNS at 127.0.0.11

Quick Decision Tables

Which storage?

NeedUse
Persistent dataNamed volume
Host directory accessBind mount
Temporary scratch--tmpfs
Read-only config-v ...:ro

Which network?

NeedUse
Defaultbridge
Max performancehost
No networknone
Service discovery by nameUser-defined bridge

Which restart policy?

PolicyBehavior
noNever restart
on-failureRestart on non-zero exit
alwaysAlways restart
unless-stoppedRestart unless manually stopped

Which build base?

NeedBase
Max compatibilitydebian:bookworm-slim
Minimal with shellalpine
Smallest, no shellscratch
No shell, some libsdistroless

One-Page Flow

IMAGE BUILD
  Dockerfile → docker build → local image → docker push → registry

CONTAINER RUN
  docker run → create namespaces + cgroups → mount rootfs → exec process

NETWORKING
  host:port → Netfilter DNAT → docker0 bridge → veth → container eth0 → app

STORAGE
  writable layer (ephemeral) | volume (persistent) | bind mount (host)

DEBUG
  docker logs | docker exec | docker inspect | nsenter + tcpdump

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!