# ContentsRun and manage · Inspect and debug · Images · Build · Dockerfile · Networking · Storage · Compose · Registry · Security · Trivy · Cleanup · Exit codes · Top 15
# Run and manage containersTask Command Run detached with name and port docker run -d --name web -p 8080:80 nginx:alpineBind only to localhost docker run -d -p 127.0.0.1:5432:5432 postgres:16-alpineInteractive shell, auto-remove docker run --rm -it alpine shEnvironment variables docker run -e KEY=val --env-file app.env imgRestart policy --restart unless-stopped (no, on-failure:5, always)Override entrypoint docker run --rm -it --entrypoint sh imgRun as specific user docker run --user 10001:10001 imgProper PID 1 (reaps zombies) docker run --init imgSet hostname / workdir --hostname h1 -w /appStop gracefully (custom timeout) docker stop -t 30 webKill with signal docker kill -s HUP webStart / restart / pause docker start web, docker restart web, docker pause webRename docker rename old newList running / all docker ps, docker ps -aCustom ps format docker ps --format 'table {{.Names}}\t{{.Status}}\t{{.Ports}}'Wait for exit code docker wait webCopy files docker cp web:/etc/nginx/nginx.conf . and docker cp ./f web:/tmp/Update limits live docker update --memory 512m --cpus 1 web
# Inspect and debugTask Command Logs, follow, last 100, with time docker logs -f --tail 100 -t webLogs since docker logs --since 10m webShell into running container docker exec -it web shRun one command docker exec web cat /etc/resolv.confFull JSON docker inspect webExit code, OOM, restarts docker inspect -f '{{.State.ExitCode}} {{.State.OOMKilled}} {{.RestartCount}}' webIP address docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}} {{end}}' webHealth history docker inspect -f '{{json .State.Health}}' webHost PID docker inspect -f '{{.State.Pid}}' webProcesses in container docker top webLive resource usage docker stats --no-streamFilesystem changes docker diff webDaemon events docker events --since 10m --filter type=containerPort mappings docker port webDebug shell-less container docker debug web or docker run --rm -it --pid container:web --net container:web nicolaka/netshootDisk usage by type docker system df -vDaemon info and storage driver docker info
# ImagesTask Command Pull specific tag or digest docker pull nginx:1.27-alpine, docker pull nginx@sha256:<digest>List with digests docker images --digestsLayers and sizes docker history --no-trunc imgConfig as JSON docker inspect --format '{{json .Config}}' img | jqTag docker tag img:dev reg.io/team/img:1.0.0Save / load tarball docker save -o img.tar img:1.0, docker load -i img.tarExport / import filesystem docker export web > fs.tar, docker import fs.tar img:flatRemove docker rmi img, docker image prune -a --filter until=168hCommit (debugging only) docker commit web img:debugSearch layers interactively dive img
# Build and buildxTask Command Basic build docker build -t app:dev .Different Dockerfile / context docker build -f docker/Dockerfile.prod -t app ./svcBuild a stage docker build --target test .Build args docker build --build-arg VERSION=1.2.3 .No cache, fresh base docker build --no-cache --pull .Plain progress logs docker build --progress=plain .Secret mount docker build --secret id=npm,src=./token.txt .SSH mount docker build --ssh default .Create builder docker buildx create --name multi --driver docker-container --useMulti-arch push docker buildx build --platform linux/amd64,linux/arm64 -t reg/app:1.0 --push .Registry cache --cache-from type=registry,ref=reg/app:cache --cache-to type=registry,ref=reg/app:cache,mode=maxGitHub Actions cache --cache-from type=gha --cache-to type=gha,mode=maxLoad multi-platform locally docker buildx build --platform linux/arm64 --load . (one platform at a time)SBOM + provenance docker buildx build --sbom=true --provenance=mode=max --push .Inspect manifest list docker buildx imagetools inspect reg/app:1.0Copy/retag without rebuild docker buildx imagetools create -t reg/app:prod reg/app:sha-abc1234Prune build cache docker builder prune --keep-storage 5GB
# Dockerfile referenceInstruction Notes FROM image:tag AS namePin versions; FROM --platform=$BUILDPLATFORM for cross-compiles ARG NAME=defaultBuild-time only; before first FROM to parametrize the base ENV KEY=valuePersists into runtime WORKDIR /appCreates the directory; prefer over RUN cd COPY --chown=u:g src dstPrefer over ADD; COPY --from=stage for multi-stage RUN cmdOne layer per instruction; chain with && and clean up in the same RUN RUN --mount=type=cache,target=/root/.cachePersistent package cache across builds RUN --mount=type=secret,id=xSecret available at /run/secrets/x for that step only USER 10001:10001Use a numeric UID so Kubernetes runAsNonRoot can verify it EXPOSE 8080Documentation only; does not publish ENTRYPOINT ["app"] / CMD ["--flag"]Exec form always; CMD gives default args HEALTHCHECK --interval=15s --timeout=3s --start-period=10s --retries=3 CMD cmdExit 0 healthy, 1 unhealthy STOPSIGNAL SIGTERMSignal for docker stop LABEL org.opencontainers.image.source=URLOCI standard metadata VOLUME /dataDeclares anonymous volume; use sparingly
Production skeleton:
dockerfile Copy
# syntax=docker/dockerfile:1.7
FROM node:22-alpine AS deps
WORKDIR /app
COPY package*.json ./
RUN --mount=type=cache,target=/root/.npm npm ci --omit=dev
FROM node:22-alpine
ENV NODE_ENV=production
WORKDIR /app
COPY --from=deps --chown=node:node /app/node_modules ./node_modules
COPY --chown=node:node . .
USER node
EXPOSE 3000
HEALTHCHECK CMD node -e "fetch('http://127.0.0.1:3000/healthz').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"
CMD [ "node" , "server.js" ] # NetworkingTask Command Create user-defined bridge docker network create appnetInternal-only network docker network create --internal backendCustom subnet docker network create --subnet 172.30.0.0/24 appnetRun on network docker run -d --network appnet --name api imgAdd network alias --network-alias api-v2Connect / disconnect running docker network connect appnet web, docker network disconnect appnet webInspect members docker network inspect appnetShare another container's network docker run --network container:web nicolaka/netshootHost networking docker run --network host img (Linux only, no isolation)No networking docker run --network none imgAdd host entry --add-host db.local:10.0.0.5Reach host from container --add-host host.docker.internal:host-gatewayCustom DNS --dns 1.1.1.1
Driver Use bridgeSingle host, default; user-defined adds DNS hostNo NAT, max performance, no isolation noneFully isolated overlayMulti-host (Swarm) macvlan / ipvlanContainer gets its own L2 address on the LAN
Embedded DNS is at 127.0.0.11 on user-defined networks. Published ports use iptables DNAT: sudo iptables -t nat -L DOCKER -n.
# Volumes and mountsTask Command Create / list / inspect docker volume create pgdata, docker volume ls, docker volume inspect pgdataNamed volume -v pgdata:/var/lib/postgresql/dataBind mount (read-only) -v "$PWD/conf:/etc/app:ro"Explicit syntax --mount type=bind,src=$PWD/conf,dst=/etc/app,readonlytmpfs --tmpfs /tmp:rw,size=64mRead-only root + tmp --read-only --tmpfs /tmpBack up a volume docker run --rm -v pgdata:/data -v "$PWD":/b alpine tar czf /b/pgdata.tgz -C /data .Restore a volume docker run --rm -v pgdata:/data -v "$PWD":/b alpine tar xzf /b/pgdata.tgz -C /dataPostgres logical dump docker exec db pg_dump -U user -Fc dbname > db.dumpRemove unused volumes docker volume prune
Bind mount -v creates a missing host directory as root; --mount errors instead. Prefer --mount in scripts.
# Docker ComposeTask Command Up detached with build docker compose up -d --buildUp without building docker compose up -d --no-buildRecreate only changed docker compose up -dForce recreate docker compose up -d --force-recreateDown (keep volumes) docker compose downDown + volumes + orphans docker compose down -v --remove-orphansStatus docker compose ps -aLogs of one service docker compose logs -f --tail 100 apiExec / one-off run docker compose exec api sh, docker compose run --rm api npm testScale docker compose up -d --scale worker=3Pull / build / push docker compose pull, docker compose build --pull, docker compose pushValidate and show merged config docker compose config (use --quiet in CI)Several files docker compose -f compose.yaml -f compose.prod.yaml up -dProfile docker compose --profile debug up -dWatch mode (dev) docker compose watchWait for healthy docker compose up -d --wait
yaml Copy
name : myapp
services :
api :
build : ./api
image : ${REGISTRY}/api:${TAG:-dev}
env_file : [ ./env/api.env ]
environment :
DB_PASSWORD : ${DB_PASSWORD:?DB_PASSWORD is required}
depends_on :
db : { condition : service_healthy }
healthcheck :
test : [ " CMD " , " wget " , " -qO- " , " http://127.0.0.1:3000/healthz " ]
interval : 15s
timeout : 3s
retries : 3
start_period : 10s
restart : unless-stopped
read_only : true
tmpfs : [ /tmp ]
cap_drop : [ ALL ]
security_opt : [ " no-new-privileges:true " ]
deploy :
resources :
limits : { cpus : " 0.5 " , memory : 256M }
networks : [ frontend , backend ]
db :
image : postgres:16-alpine
volumes : [ pgdata:/var/lib/postgresql/data ]
healthcheck :
test : [ " CMD-SHELL " , " pg_isready -U $${POSTGRES_USER} " ]
networks : [ backend ]
networks :
frontend :
backend :
internal : true
volumes :
pgdata : Variable rules: .env feeds ${VAR} interpolation in compose.yaml; env_file: and environment: feed the container. Escape a literal $ as $$. Precedence (high to low): docker compose run -e, environment:, env_file:, image ENV.
# Registry and taggingTask Command Login (token via stdin) echo "$TOKEN" | docker login ghcr.io -u USER --password-stdinLogout docker logout ghcr.ioPush all tags docker push --all-tags ghcr.io/user/appGet digest docker inspect --format '{{index .RepoDigests 0}}' ghcr.io/user/app:1.0.0Pull by digest docker pull ghcr.io/user/app@sha256:<digest>List remote tags crane ls ghcr.io/user/appCopy between registries crane copy src dstLocal registry docker run -d -p 5000:5000 --name registry registry:2
Reference format: [registry[:port]/]namespace/name[:tag][@sha256:digest].
Tag scheme we use in production: 1.4.2 (immutable release), 1.4 (moving minor), sha-abc1234 (traceability, unique per commit), main or edge (moving, non-prod only). No latest in deploy manifests. Deploy by digest when you need a guarantee.
# Security hardeningControl Flag or setting Non-root USER 10001:10001 or --user 10001:10001Read-only root FS --read-only --tmpfs /tmpDrop all capabilities --cap-drop ALL (add back, e.g. --cap-add NET_BIND_SERVICE)Block privilege escalation --security-opt no-new-privileges:trueDefault seccomp profile on by default; custom: --security-opt seccomp=profile.json Resource limits --memory 256m --cpus 0.5 --pids-limit 200Never --privileged, mounting /var/run/docker.sock, --network host unless requiredSecrets BuildKit --mount=type=secret; at runtime Compose secrets: or a secret manager, not ENV Pin bases FROM node:22.11-alpine3.20 (or @sha256:)User namespace remap "userns-remap": "default" in /etc/docker/daemon.jsonRootless Docker dockerd-rootless-setuptool.sh installImage trust cosign sign, cosign verify, deploy by digest
# TrivyTask Command Scan image, gate for CI trivy image --severity HIGH,CRITICAL --ignore-unfixed --exit-code 1 app:1.0Scan with secrets and misconfig trivy image --scanners vuln,secret,misconfig app:1.0Scan Dockerfile / Compose / IaC trivy config .Scan source dependencies trivy fs --scanners vuln,secret .SBOM (CycloneDX / SPDX) trivy image --format cyclonedx -o sbom.json app:1.0 and --format spdx-jsonScan an SBOM later trivy sbom sbom.jsonJSON report trivy image -f json -o report.json app:1.0Ignore file .trivyignore with one CVE per line, reason in a commentRefresh DB trivy image --download-db-onlyRun as container docker run --rm -v /var/run/docker.sock:/var/run/docker.sock -v trivy-cache:/root/.cache aquasec/trivy image app:1.0
# CleanupTask Command Remove stopped containers docker container prune -fRemove dangling images docker image prune -fRemove all unused images docker image prune -a -fRemove unused networks docker network prune -fRemove unused volumes docker volume prune -fEverything unused (no volumes) docker system prune -fEverything incl. volumes docker system prune -a --volumes -f (destructive)Remove all containers docker rm -f $(docker ps -aq)Disk usage docker system dfLog rotation --log-opt max-size=10m --log-opt max-file=3
# Exit codesCode Meaning 0 Clean exit 1 Application error (read the logs) 125 docker run itself failed (bad flag, daemon error)126 Command found but not executable (permissions) 127 Command not found (wrong CMD or missing binary) 137 SIGKILL: OOM kill, docker kill, or stop timeout exceeded 139 SIGSEGV: segmentation fault 143 SIGTERM: graceful stop
# Frequent error messagesMessage Meaning and quick fix Cannot connect to the Docker daemon at unix:///var/run/docker.sockDaemon down or no permission: systemctl status docker, add user to docker group permission denied while trying to connect to the Docker daemon socketNot in docker group; sudo usermod -aG docker $USER and re-login Bind for 0.0.0.0:80 failed: port is already allocatedHost port taken: ss -ltnp | grep :80 exec format errorWrong CPU architecture or missing shebang: build with --platform no space left on devicedocker system df, then prune; check /var/lib/dockerpull access denied / manifest unknownWrong name or tag, or not logged in OCI runtime create failed ... executable file not found in $PATHBad CMD/ENTRYPOINT or distroless without shell network ... not found / Pool overlaps with other oneStale network or subnet clash: docker network prune, choose another subnet
# Top 15 interview one-liners
Container vs VM: a container is an isolated process sharing the host kernel (namespaces plus cgroups); a VM runs its own kernel on virtualized hardware.
Image vs container: an image is an immutable stack of layers plus config; a container is an image plus a writable layer plus a running process.
CMD vs ENTRYPOINT: ENTRYPOINT is the executable, CMD is its default arguments; docker run img args replaces CMD and appends to ENTRYPOINT.
COPY vs ADD: use COPY; ADD also fetches URLs and auto-extracts archives, which is surprising and less auditable.
Shrinking an image: multi-stage build, small base (alpine, slim, distroless), .dockerignore, no package caches, combine and clean up inside one RUN.
Why order matters: cache is invalidated at the first changed layer, so copy dependency manifests and install before copying source.
Data persistence: use named volumes for databases, bind mounts for dev, tmpfs for scratch; container filesystem is ephemeral.
Container-to-container communication: put them on a user-defined network and use service names, because Docker's embedded DNS only exists there.
EXPOSE vs -p: EXPOSE is documentation; -p host:container actually publishes the port through iptables DNAT.
Run as non-root: set a numeric USER, drop capabilities, no-new-privileges, read-only root filesystem, ports above 1024.
Secrets: never in ENV, ARG or COPY; they stay in docker history. Use BuildKit secret mounts at build time and secret managers or Compose secrets at runtime.
Exit code 137: SIGKILL, usually the OOM killer; confirm with docker inspect -f '{{.State.OOMKilled}}' and raise the limit or fix the leak.
depends_on pitfall: it orders start, not readiness; add a healthcheck and condition: service_healthy.
Tagging in production: immutable semver plus git SHA tag, deploy by version or digest, never latest; scan with Trivy and fail on fixable HIGH/CRITICAL.
Why docker stop is slow: the app is ignoring SIGTERM (often because a shell is PID 1); use exec-form CMD, handle the signal, or add --init.