Contents

Docker Cheat Sheet

Every Docker command and flag, searchable across the whole page and copy-ready.

By Bogdan SanduUpdated August 2, 2026

Images

Pull & List Images

BEG

Pull an image from Docker Hub

docker pull nginx

Pull a specific tag

docker pull nginx:1.25-alpine

List all local images

docker images

List with full digest --digests

docker images --digests

Filter by name --filter

docker images --filter "reference=nginx*"

Build Images

BEGINTADV

Build from current directory -t

docker build -t myapp:latest .

Build from specific Dockerfile -f

docker build -f Dockerfile.prod -t myapp:prod .

Build with arguments --build-arg

docker build --build-arg NODE_ENV=production -t myapp .

Build without cache --no-cache

docker build --no-cache -t myapp .

Enable BuildKit for faster builds

DOCKER_BUILDKIT=1 docker build -t myapp .

Rendered

BuildKit enables parallel layer builds, cache mounts, and better output. Set globally: export DOCKER_BUILDKIT=1

BuildKit cache mount --mount=type=cache

RUN --mount=type=cache,target=/root/.npm \
    npm ci

Rendered

Caches the target dir between builds. NOT included in the final image. Common targets: /root/.npm npm /root/.cache/pip pip /var/cache/apt apt

Multi-platform build --platform

docker buildx build \
  --platform linux/amd64,linux/arm64 \
  -t myapp:latest --push .

Inspect, Tag, Save & Remove

BEGINTADV

Tag an image

docker tag myapp:latest myrepo/myapp:v1.0

Inspect full image metadata

docker inspect myapp:latest

Inspect - get image ID --format

docker inspect --format="{{.Id}}" myapp:latest

Rendered

More --format examples: OS/arch: --format="{{.Os}}/{{.Architecture}}" Container IP: --format="{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}" Env vars: --format="{{range .Config.Env}}{{.}}{{println}}{{end}}"

Show layer history --no-trunc

docker history --no-trunc myapp:latest

Save image to tar -o

docker save -o myapp.tar myapp:latest

Load image from tar -i

docker load -i myapp.tar

Export container filesystem docker export

docker export mycontainer -o snapshot.tar

Rendered

export vs save: save = image layers + history export = flat container filesystem, no history Import back: docker import snapshot.tar myapp:restored

Import tar as new image

docker import snapshot.tar myapp:restored

Commit container as new image docker commit

docker commit -m "added config" mycontainer myapp:v2

Rendered

Creates an image from a container's current state. Good for snapshots. Prefer Dockerfiles for reproducibility. Flags: -m message -a author

Remove an image

docker rmi myapp:latest

Containers

Run Containers

BEGINTADV

Run a container

docker run nginx

Run detached -d

docker run -d nginx

Named container with port mapping --name -p

docker run -d --name web -p 8080:80 nginx

Interactive shell -it

docker run -it ubuntu bash

Environment variables -e

docker run -e NODE_ENV=production -e PORT=3000 myapp

Volume mount -v

docker run -v /host/path:/container/path nginx

Auto-remove on exit --rm

docker run --rm ubuntu echo hello

Resource limits --memory --cpus

docker run -d --memory=512m --cpus=1.5 myapp

Restart policy --restart

docker run -d --restart unless-stopped nginx

Rendered

Policies: no never restart (default) always always restart on-failure only on non-zero exit on-failure:3 up to 3 times unless-stopped unless manually stopped

Manage & Inspect Containers

BEGINTADV

List running containers

docker ps

List all containers -a

docker ps -a

Stop / start / restart

docker stop web
docker start web
docker restart web

Remove a stopped container

docker rm web

Force remove -f

docker rm -f web

View logs

docker logs web

Follow logs -f --tail

docker logs -f --tail 100 web

Execute command in container -it

docker exec -it web bash

Copy host to container

docker cp ./file.txt web:/app/file.txt

Copy container to host

docker cp web:/app/logs/out.log ./out.log

Show changed files docker diff

docker diff web

Rendered

Shows filesystem changes vs the original image. A = Added C = Changed D = Deleted Useful before docker commit.

Resource usage stats

docker stats web

Get container IP --format

docker inspect --format="{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}" web

Running processes in container

docker top web

Pause / unpause

docker pause web
docker unpause web

Volumes & Networks

Volumes

BEGINT

Create a named volume

docker volume create mydata

List all volumes

docker volume ls

Mount a named volume -v

docker run -v mydata:/app/data myapp

Read-only mount :ro

docker run -v mydata:/app/data:ro myapp

Inspect a volume

docker volume inspect mydata

Remove a volume

docker volume rm mydata

Remove all unused volumes

docker volume prune

Networks

INTADV

List networks

docker network ls

Create a bridge network

docker network create mynet

Run on custom network --network

docker run -d --network mynet --name app myapp

Connect container to network

docker network connect mynet web

Disconnect container from network

docker network disconnect mynet web

Inspect network containers --format

docker network inspect --format="{{range .Containers}}{{.Name}} {{.IPv4Address}}{{println}}{{end}}" mynet

Create overlay network (Swarm)

docker network create -d overlay myoverlay

Remove unused networks

docker network prune

Compose

Core Compose Commands

BEGINTADV

Start services detached -d

docker compose up -d

Stop and remove containers

docker compose down

Stop and remove including volumes -v

docker compose down -v

Follow all service logs -f

docker compose logs -f

List running services

docker compose ps

Rebuild before starting --build

docker compose up -d --build

Scale a service --scale

docker compose up -d --scale worker=3

One-off command --rm

docker compose run --rm app python manage.py migrate

Use alternate file -f

docker compose -f docker-compose.prod.yml up -d

Validate resolved config

docker compose config

docker-compose.yml Structure

BEGINTADV

Basic service definition

services:
  web:
    image: nginx:alpine
    ports:
      - "8080:80"

Service with build, env, volumes, depends_on

services:
  app:
    build: .
    environment:
      - NODE_ENV=production
    volumes:
      - ./src:/app/src
    depends_on:
      - db
  db:
    image: postgres:15
    volumes:
      - pgdata:/var/lib/postgresql/data
volumes:
  pgdata:

Health check in compose

services:
  db:
    image: postgres:15
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 10s
      timeout: 5s
      retries: 5

Dockerfile

Core Instructions

BEGINTADV

Base image FROM

FROM node:20-alpine

Working directory WORKDIR

WORKDIR /app

Copy files COPY

COPY package*.json ./
COPY . .

Run a command RUN

RUN npm install

Document a port EXPOSE

EXPOSE 3000

Default command CMD

CMD ["node", "server.js"]

Non-overridable entrypoint ENTRYPOINT

ENTRYPOINT ["python", "app.py"]

Rendered

ENTRYPOINT always runs, cannot be overridden. CMD provides default args, overridden at runtime. Combined: ENTRYPOINT ["python", "app.py"] CMD ["--port", "8080"] docker run myapp = python app.py --port 8080 docker run myapp --port 9000 = python app.py --port 9000

Environment variable ENV

ENV NODE_ENV=production PORT=3000

Build-time variable ARG

ARG VERSION=1.0
RUN echo "Version: $VERSION"

Volume mount point VOLUME

VOLUME ["/data"]

Label metadata LABEL

LABEL maintainer="team@example.com" version="1.0"

Health check HEALTHCHECK

HEALTHCHECK --interval=30s --timeout=5s \
  CMD curl -f http://localhost:3000/health || exit 1

Multi-Stage Builds

ADV

Multi-stage Node build AS --from

# Build stage
FROM node:20 AS builder
WORKDIR /app
COPY . .
RUN npm ci && npm run build

# Production stage
FROM node:20-alpine AS runner
WORKDIR /app
COPY --from=builder /app/dist ./dist
CMD ["node", "dist/server.js"]

.dockerignore example

node_modules
.git
.env
*.log
dist

Registry & Hub

Docker Hub

BEGINT

Login to Docker Hub

docker login

Push image

docker push myrepo/myapp:v1.0

Search Docker Hub

docker search nginx

Logout

docker logout

Private Registry

INTADV

Login to private registry

docker login registry.example.com

Tag for private registry

docker tag myapp registry.example.com/myapp:v1.0

Push to private registry

docker push registry.example.com/myapp:v1.0

Run a local registry

docker run -d -p 5000:5000 --name registry registry:2

System & Cleanup

System Info

BEGINT

Docker version

docker version

System-wide info

docker info

Disk usage summary

docker system df

Verbose disk usage -v

docker system df -v

Cleanup

INTADV

Remove stopped containers

docker container prune

Remove dangling images

docker image prune

Remove all unused images -a

docker image prune -a

Remove everything unused ⚠

docker system prune -a --volumes

Remove images older than 24h --filter

docker image prune -a --filter "until=24h"

Swarm

Swarm Init & Nodes

ADV

Initialize a Swarm

docker swarm init --advertise-addr MANAGER-IP

Get worker join token

docker swarm join-token worker

Join as worker node

docker swarm join --token TOKEN MANAGER-IP:2377

List nodes

docker node ls

Leave the Swarm --force

docker swarm leave --force

Services & Stacks

ADV

Deploy a service --replicas

docker service create --replicas 3 -p 80:80 --name web nginx

List services

docker service ls

Scale a service

docker service scale web=5

Rolling image update --image

docker service update --image nginx:latest web

Deploy stack from compose file

docker stack deploy -c docker-compose.yml mystack

List stacks

docker stack ls

Remove a stack

docker stack rm mystack

Secrets Management

ADV

Create secret from stdin

echo "mysecretpassword" | docker secret create db_pass -

Create secret from file

docker secret create ssl_cert ./cert.pem

List secrets

docker secret ls

Remove a secret

docker secret rm db_pass

Use secret in a service --secret

docker service create --name app --secret db_pass myapp

Rendered

Secret mounted inside container at: /run/secrets/db_pass Read in your app: fs.readFileSync('/run/secrets/db_pass', 'utf8').trim() Requires Swarm mode.

This Docker cheat sheet covers every command you need, from pulling images to managing full Swarm clusters. No filler. Just commands.

What's inside:

  • Images - build, pull, tag, save, export, commit, multi-platform builds

  • Containers - run flags, exec, logs, copy, diff, stats, resource limits

  • Volumes & Networks - named volumes, bind mounts, bridge and overlay networks

  • Docker Compose - full CLI reference plus docker-compose.yml structure examples

  • Dockerfile - every instruction explained, multi-stage builds, BuildKit cache mounts

  • Registry & Hub - push, pull, private registries, run your own local registry

  • System & Cleanup - prune commands, disk usage, safe and nuclear cleanup options

  • Swarm - init, services, stacks, rolling updates, secrets management

Built for all skill levels. Filter by Beginner, Intermediate, or Advanced to cut the noise. Search across all tabs instantly with /. Every snippet has a one-click copy button.

Some commands include a preview that explains flags, output format, or gotchas. The --format Go template examples, restart policies, ENTRYPOINT vs CMD differences, and BuildKit cache mount behavior are all covered inline.

No login. No paywall. Free to use.

What is Docker

Docker is an open-source platform for building, running, and shipping applications inside containers.

A container packages an application together with its libraries, dependencies, and configuration files so it runs the same on any machine - your laptop, a test server, or production.

Before Docker, "works on my machine" was a real problem. Dependency mismatches, OS differences, missing runtime versions. Docker solves all of that.

It's not a virtual machine. Containers share the host OS kernel, which makes them faster to start and much lighter on resources.


What Are the Core Components of Docker

Docker isn't one thing. It's a set of parts that work together.

Docker Daemon

The background service running on your host. It does the actual work: creates containers, manages images, handles networking and volumes.

You don't interact with it directly. The Docker client talks to it over a socket.

Docker Client

The CLI tool you use. When you run docker run or docker build, the client sends that instruction to the daemon.

Docker Images

Read-only templates used to create containers. Built from a Dockerfile, layer by layer.

Images live in registries. You pull them down, run them, or build your own.

Docker Containers

A running instance of an image. Isolated from other containers and from the host - its own filesystem, network, and process space.

Containers are stateless by default. Data doesn't survive a restart unless you use volumes.

Docker Registries

Where images are stored and distributed. Docker Hub is the default public registry - thousands of official and community images.

You can also run a private container registry for internal images.


Docker Installation Commands

How to Install Docker on Linux

curl -fsSL https://get.docker.com | sh
sudo usermod -aG docker $USER

Log out and back in after adding your user to the docker group. Otherwise every command needs sudo.

How to Install Docker on macOS

Download Docker Desktop from docker.com. Includes the daemon, CLI, and Docker Compose in one package.

How to Install Docker on Windows

Docker Desktop on Windows runs containers through WSL 2. Enable WSL 2 before installing, or containers will be significantly slower.

How to Verify Docker Installation

docker --version
docker info

docker info shows daemon status, container count, and system-level details. If it hangs, the daemon isn't running.


Docker Container Commands

How to Create and Run a Docker Container

docker run is the most-used command in the Docker CLI. It pulls the image (if not cached), creates a container, and starts it.

docker run Syntax and Options

docker run [OPTIONS] IMAGE [COMMAND]

Common flags: -d (detached), -p (port mapping), -e (environment variable), -v (volume), --name (container name), --rm (auto-remove on exit).

How to Run a Container in Detached Mode

docker run -d nginx

Detached mode runs the container in the background. You get the container ID back. Use docker logs to see output.

How to Run a Container with Port Mapping

docker run -d -p 8080:80 nginx

Format: HOST_PORT:CONTAINER_PORT.

The container exposes port 80 internally. Port 8080 on your machine forwards to it. Open http://localhost:8080 to confirm.

How to Run a Container with Environment Variables

docker run -e DB_HOST=localhost -e DB_PORT=5432 myapp

Pass config without hardcoding it into the image. Critical for production environment deployments - you want the same image across environments, with different env vars per environment. That's environment parity.

How to Run a Container with a Volume

docker run -v myvolume:/app/data myapp

Volumes persist data outside the container lifecycle. Use named volumes (above) or bind mounts for dev work.

How to List and Manage Running Containers

How to List Running Containers

docker ps

Shows container ID, image, command, uptime, ports, and name. Add -a to include stopped containers.

How to List All Containers Including Stopped Ones

docker ps -a

Stopped containers still exist until you remove them. docker ps -a -q returns only IDs - useful for bulk operations.

How to Stop a Running Container

docker stop CONTAINER_ID

Sends SIGTERM, waits 10 seconds, then sends SIGKILL if the container hasn't exited. Graceful by default.

How to Start a Stopped Container

docker start CONTAINER_ID

Restarts a stopped container with its original configuration. Doesn't re-pull the image.

How to Restart a Container

docker restart CONTAINER_ID

Stop + start in one command. Useful after changing environment variables or config files that require a full restart.

How to Pause and Unpause a Container

docker pause CONTAINER_ID
docker unpause CONTAINER_ID

Freezes all processes inside the container without stopping it. Rarely needed in day-to-day work, but handy for snapshots.

How to Remove Docker Containers

How to Remove a Stopped Container

docker rm CONTAINER_ID

Only works on stopped containers. Add -f to force-remove a running one.

How to Remove All Stopped Containers

docker container prune

Cleans up all stopped containers at once. Prompts for confirmation unless you pass -f.

How to Force Remove a Running Container

docker rm -f CONTAINER_ID

Skips the graceful stop. Use when a container is stuck and docker stop isn't working.

How to Inspect and Debug Containers

How to View Container Logs

docker logs CONTAINER_ID

Prints all stdout/stderr output since the container started. Add --tail 50 to limit output, or --since 1h for a time window.

How to Follow Container Logs in Real Time

docker logs -f CONTAINER_ID

Live-streams log output. Works like tail -f. Hit Ctrl+C to exit - the container keeps running.

How to Execute a Command Inside a Running Container

docker exec CONTAINER_ID ls /app

Runs a one-off command in a running container without opening a full shell.

How to Open a Shell Inside a Container

docker exec -it CONTAINER_ID /bin/bash

-it = interactive + TTY. Use /bin/sh if the image doesn't include bash (common in Alpine-based images).

How to Inspect Container Details

docker inspect CONTAINER_ID

Returns full JSON: network config, mounts, environment variables, restart policy, and more. Pipe to jq for readable output.

How to View Container Resource Usage

docker stats

Live CPU, memory, network I/O, and block I/O for all running containers. Add a container name/ID to watch a specific one.


Docker Image Commands

How to Pull and Push Docker Images

How to Pull an Image from Docker Hub

docker pull ubuntu

Pulls the latest tag by default. Always be specific in production - latest changes.

How to Pull a Specific Image Version

docker pull node:20-alpine

Tag format: IMAGE:TAG. Alpine variants are much smaller than full distributions. node:20-alpine is ~50MB vs ~300MB for node:20.

How to Push an Image to Docker Hub

docker tag myapp yourusername/myapp:1.0
docker push yourusername/myapp:1.0

Tag before pushing. The registry path is username/repo:tag. You need to be logged in via docker login.

How to List and Remove Docker Images

How to List All Docker Images

docker images

Shows repository, tag, image ID, creation date, and size. Add -a to include intermediate layers.

How to Remove a Docker Image

docker rmi IMAGE_ID

Fails if a container (even stopped) is using the image. Remove the container first, or add -f.

How to Remove All Unused Images

docker image prune -a

Removes all images not referenced by any container. -a includes untagged and tagged images with no containers. Significant disk space savings on dev machines.

How to Tag and Search Docker Images

How to Tag a Docker Image

docker tag SOURCE_IMAGE TARGET_IMAGE:TAG

Tagging is how you version images and prepare them for a registry push. Same image, multiple tags - no duplication on disk.

How to Search Docker Hub for Images

docker search postgres

Returns name, description, stars, and official status. Official images are maintained by Docker or the upstream vendor - prefer them over random community images.

Dockerfile Commands and Syntax

What is a Dockerfile

A Dockerfile is a plain text configuration file that defines how a Docker image gets built - base image, dependencies, file copies, and startup command, all in one place.

Every line creates a new image layer. Order matters: put rarely-changing instructions first to maximize build cache hits, per the official Dockerfile reference.

FROM

FROM node:20-alpine

Every Dockerfile starts with FROM. Sets the base image. Use slim or Alpine variants in production - smaller attack surface, faster pulls.

RUN

RUN apt-get update && apt-get install -y curl

Executes a command during the build. Chain commands with && to keep them on one layer and reduce image size.

CMD

CMD ["node", "server.js"]

Default command when the container starts. Only one CMD per Dockerfile. Gets overridden if you pass a command to docker run.

ENTRYPOINT

ENTRYPOINT ["python", "app.py"]

Like CMD, but harder to override. Use ENTRYPOINT for the main process and CMD for default arguments to it.

COPY

COPY ./src /app/src

Copies files from the build context into the image. Prefer COPY over ADD unless you need archive extraction.

ADD

ADD archive.tar.gz /app/

Like COPY but also extracts .tar archives and supports URLs. Use sparingly - COPY is more predictable.

ENV

ENV NODE_ENV=production

Sets environment variables available at build time and runtime. Baked into the image, visible in docker inspect.

EXPOSE

EXPOSE 3000

Documents which port the container listens on. Doesn't actually publish the port - that's -p in docker run.

WORKDIR

WORKDIR /app

Sets the working directory for subsequent RUN, CMD, COPY, and ADD instructions. Creates the directory if it doesn't exist.

ARG

ARG VERSION=1.0

Build-time variable. Passed with --build-arg VERSION=2.0. Not available at runtime - use ENV for that.

VOLUME

VOLUME ["/app/data"]

Declares a mount point. Docker creates an anonymous volume at this path if no volume is mounted at run time.

LABEL

LABEL maintainer="team@example.com"

Adds metadata to the image. Useful for CI pipelines, image audits, and filtering with docker images --filter.

USER

USER node

Switches to a non-root user for all following instructions. Running as root inside containers is a security risk - always set USER before CMD.

HEALTHCHECK

HEALTHCHECK CMD curl -f http://localhost:3000/health || exit 1

Tells Docker how to test if the container is healthy. Failed health checks show up in docker ps under STATUS.

ONBUILD

ONBUILD COPY . /app

Triggers a deferred instruction when the image is used as a base. Useful for reusable base images, tricky to debug otherwise.

How to Build an Image from a Dockerfile

docker build Basic Syntax

docker build .

Builds from the Dockerfile in the current directory. The . is the build context - everything in that directory gets sent to the daemon.

How to Build with a Custom Tag

docker build -t myapp:1.0 .

Always tag your builds. Untagged images become <none> and clutter docker images.

How to Build from a Specific Dockerfile Path

docker build -f ./docker/Dockerfile.prod -t myapp:prod .

Useful when you maintain multiple Dockerfiles per environment (dev, staging, prod) inside the same codebase.

How to Build Without Cache

docker build --no-cache -t myapp:fresh .

Forces a full rebuild. Use when a RUN apt-get layer is stale or you suspect a cached layer has outdated dependencies.

Dockerfile Best Practices

How to Minimize Image Layers

Chain RUN commands with && and clean up in the same layer:

RUN apt-get update && apt-get install -y curl \
    && rm -rf /var/lib/apt/lists/*

Each RUN is a layer. Cleanup in a separate RUN doesn't shrink the image - the data still exists in the previous layer.

How to Use Multi-Stage Builds

FROM node:20 AS builder
WORKDIR /app
COPY . .
RUN npm run build

FROM node:20-alpine
COPY --from=builder /app/dist /app/dist
CMD ["node", "/app/dist/server.js"]

Multi-stage builds keep build tools out of the final image. The builder stage compiles everything; the second stage ships only the output. Final image can drop from 800MB to under 100MB.

How to Reduce Final Image Size

Use Alpine base images, .dockerignore to exclude node_modules and .git, and multi-stage builds.

Run docker image history IMAGE_ID to see which layers are eating the most space.


Docker Volume Commands

What is a Docker Volume

A Docker volume is persistent storage that exists outside the container filesystem. Data written to a volume survives container stops, restarts, and removals. Databases are the usual case; the PostgreSQL cheat sheet shows a Compose file with a named volume and a health check.

Three storage types: named volumes (managed by Docker), bind mounts (host path mapped into container), tmpfs mounts (in-memory only).

How to Create and Manage Volumes

How to Create a Volume

docker volume create myvolume

Creates a named volume stored at Docker's default volume path. On Linux: /var/lib/docker/volumes/.

How to List All Volumes

docker volume ls

Shows all volumes, including anonymous ones created by containers. Anonymous volumes have random hex IDs - hard to track, clean up regularly.

How to Inspect a Volume

docker volume inspect myvolume

Returns mount point, creation date, driver, and labels in JSON. Tells you exactly where Docker volumes are stored on the host.

How to Remove a Volume

docker volume rm myvolume

Fails if a container is using the volume. Stop and remove the container first.

How to Remove All Unused Volumes

docker volume prune

Deletes all volumes not attached to any container. Permanent - no recovery. Double-check before running in any environment with real data.

How to Mount Volumes in Containers

How to Use a Named Volume with docker run

docker run -v myvolume:/app/data myapp

myvolume mounts at /app/data inside the container. If the volume doesn't exist, Docker creates it automatically.

How to Use a Bind Mount

docker run -v $(pwd)/src:/app/src myapp

Maps a host directory directly into the container. Standard practice in local development - edit files on the host, changes reflect instantly inside the container.


Docker Network Commands

What is a Docker Network

A Docker network is an isolated communication layer between containers. Containers on the same network reach each other by container name - no IP addresses needed.

Docker Network Types

Bridge Network

The default. Containers on the same bridge network communicate with each other; isolated from containers on other networks.

Run docker network inspect bridge to see which containers are connected.

Host Network

docker run --network host nginx

Container shares the host's network stack directly. No port mapping needed - but no isolation either. Linux only; doesn't work on Docker Desktop for Mac/Windows.

None Network

docker run --network none myapp

Completely disables networking. Use for batch jobs or security-sensitive workloads that don't need any network access.

Overlay Network

Used with Docker Swarm for multi-host networking. Containers on different physical hosts communicate as if they're on the same network. Requires Swarm mode.

How to Create and Manage Docker Networks

How to Create a Network

docker network create mynetwork

Creates a user-defined bridge network. Always use named networks in Compose or multi-container setups - default bridge doesn't support DNS resolution by container name.

How to List Networks

docker network ls

Shows all networks, their driver, and scope. You'll always see bridge, host, and none by default.

How to Inspect a Network

docker network inspect mynetwork

Returns connected containers, IP ranges, gateway, and driver config.

How to Connect a Container to a Network

docker network connect mynetwork CONTAINER_ID

Attaches a running container to an additional network. A container can belong to multiple networks simultaneously.

How to Disconnect a Container from a Network

docker network disconnect mynetwork CONTAINER_ID

Removes the container from the network without stopping it.

How to Remove a Network

docker network rm mynetwork

Fails if any container is still connected. Disconnect all containers first.


Docker Compose Commands

What is Docker Compose

Docker Compose is a tool for defining and running multi-container applications from a single YAML file.

One docker compose up starts your entire stack - app, database, cache, proxy - with correct networks and volumes, every time.

How to Use Docker Compose

docker compose up

docker compose up -d

Builds images (if needed), creates networks and volumes, starts all services. -d runs in detached mode.

docker compose down

docker compose down

Stops and removes containers and networks. Add -v to also delete volumes - careful with database data.

docker compose build

docker compose build

Rebuilds images without starting containers. Use --no-cache to force a clean build.

docker compose start and stop

docker compose start
docker compose stop

Start/stop existing containers without removing them. Unlike up/down, these don't recreate anything.

docker compose ps

docker compose ps

Lists containers for the current Compose project with their state and port bindings.

docker compose logs

docker compose logs -f servicename

Tails logs from a specific service. Omit the service name to see all services at once.

docker compose exec

docker compose exec app /bin/sh

Opens a shell in a running service container. Equivalent to docker exec -it but references the service name from the Compose file.

docker compose pull

docker compose pull

Pulls updated images for all services defined in the Compose file without starting them.

docker compose restart

docker compose restart servicename

Restarts a specific service. Doesn't rebuild the image or re-read the Compose file - use up --force-recreate for that.

docker-compose.yml File Structure

version

version: "3.9"

Specifies the Compose file format version. Version 3.x is standard for most use cases. Omit it entirely in newer Compose V2 - it's deprecated.

services

services:
  app:
    image: myapp:latest

Defines each container in your stack. Every service gets its own container, network alias, and configuration block.

networks

networks:
  backend:
    driver: bridge

Defines custom networks for the stack. Services on the same named network communicate by service name.

volumes

volumes:
  db_data:

Declares named volumes for the stack. Referenced in service definitions under volumes:.

environment

environment:
  - DATABASE_URL=postgres://user:pass@db:5432/mydb

Sets environment variables per service. Use an .env file with env_file: to keep secrets out of the Compose file.

depends_on

depends_on:
  - db

Controls startup order. app starts after db - but doesn't wait for db to be ready. Pair with a health check or retry logic in your app.

ports

ports:
  - "8080:80"

Maps host ports to container ports. Same format as -p in docker run.

build context

build:
  context: .
  dockerfile: Dockerfile.prod

Tells Compose to build the image from a local Dockerfile instead of pulling from a registry.


Docker Registry Commands

How to Log In and Out of Docker Hub

docker login
docker logout

docker login prompts for your Docker Hub username and password (or token). Credentials are stored in ~/.docker/config.json.

Use access tokens instead of passwords - revokable, scoped, and safer for CI environments.

How to Work with Private Registries

docker login registry.example.com
docker pull registry.example.com/myapp:1.0

Specify the registry hostname before the image name. Works with AWS ECR, GCP Artifact Registry, GitHub Container Registry, or any self-hosted registry.


Docker System and Cleanup Commands

How to Free Up Docker Disk Space

Docker accumulates stopped containers, unused images, dangling volumes, and abandoned networks. Left unchecked on dev machines, it can consume 10–20GB easily.

docker system df

docker system df

Shows disk usage by images, containers, volumes, and build cache. Run this first to see where the space is going.

docker system prune

docker system prune

Removes stopped containers, dangling images, unused networks, and build cache in one command. Add -a to also remove unused (not just dangling) images.

How to Remove Unused Containers, Images, and Volumes Together

docker system prune -a --volumes

Full cleanup. Everything not currently in use gets removed. Don't run this on a shared build server without checking first.

How to View Docker System Information

docker info

docker info

Shows daemon version, OS, kernel, total containers, images, storage driver, and resource limits. First thing to check when something behaves unexpectedly.

docker version

docker version

Prints client and server versions separately. Useful when debugging compatibility issues between Docker CLI and daemon.


Docker Swarm Commands

What is Docker Swarm

Docker Swarm is Docker's built-in container orchestration tool. It turns a group of Docker hosts into a single cluster, distributing containers across nodes automatically.

Less complex than Kubernetes. Good fit for smaller teams already using Docker who need basic multi-host deployment without the overhead.

How to Initialize and Manage a Swarm

docker swarm init

docker swarm init --advertise-addr 192.168.1.10

Turns the current host into a Swarm manager. Outputs a join token for worker nodes.

docker swarm join

docker swarm join --token SWMTKN-... 192.168.1.10:2377

Joins a worker node to the swarm cluster. Run this on each additional host.

docker node ls

docker node ls

Lists all nodes in the swarm with their role (manager/worker), status, and availability. Manager-only command.

docker service create

docker service create --replicas 3 -p 80:80 nginx

Creates a Swarm service - a container that runs across multiple nodes with automatic load balancing and restart.

docker service ls

docker service ls

Lists all services in the swarm with replica counts and port mappings.

docker service scale

docker service scale myservice=5

Scales a service to the specified number of replicas. Swarm distributes the new containers across available nodes automatically.

docker stack deploy

docker stack deploy -c docker-compose.yml mystack

Deploys a full Compose file to the swarm as a stack. The Swarm equivalent of docker compose up.


Docker Compose vs Docker Swarm

Docker Compose

Docker Swarm

Use case

Local dev, single host

Multi-host production clusters

Scaling

Manual, single machine

Automatic, across nodes

Config file

docker-compose.yml

Same format, deployed via docker stack deploy

Networking

Bridge (local)

Overlay (multi-host)

Complexity

Low

Medium

When to use

Dev environments, simple deployments

When you need high availability across multiple hosts

Compose and Swarm use the same file format. A Compose file written for local development can often be deployed to Swarm with minimal changes.


Docker Security Best Practices

How to Run Containers as Non-Root Users

Add USER to your Dockerfile before CMD. Running as root inside a container is the default - and a real risk if the container is ever compromised.

RUN addgroup -S appgroup && adduser -S appuser -G appgroup
USER appuser

How to Scan Docker Images for Vulnerabilities

docker scout cves myapp:latest

Docker Scout (built into Docker Desktop) scans images for known CVEs. Integrate into your build pipeline to catch vulnerabilities before app deployment.

How to Use Read-Only Filesystems

docker run --read-only myapp

Mounts the container filesystem as read-only. Attackers can't write malicious files if they break in. Combine with --tmpfs /tmp for processes that need temporary write access.

How to Limit Container Resources (CPU and Memory)

docker run --memory="512m" --cpus="1.0" myapp

Without limits, a single runaway container can starve the entire host. Always set memory and CPU limits in production.

Use docker stats to understand actual consumption before setting limits - guessing too low causes unexpected container kills.

FAQ on Docker Cheat Sheets

What is the most useful Docker command for beginners?

docker run is the one to learn first. It pulls an image, creates a Docker container, and starts it in a single command. Once you understand its flags - -d, -p, -v, -e - everything else clicks into place.

What is the difference between docker stop and docker kill?

docker stop sends SIGTERM and waits up to 10 seconds for a graceful shutdown. docker kill sends SIGKILL immediately - no waiting. Use stop by default; kill only when a container is stuck and unresponsive.

How do you remove all stopped containers at once?

Run docker container prune. It deletes every stopped container in one shot and prompts for confirmation. Add -f to skip the prompt. For a full cleanup including unused images and volumes, use docker system prune -a --volumes.

What is the difference between CMD and ENTRYPOINT in a Dockerfile?

CMD sets the default command and gets overridden easily at runtime. ENTRYPOINT defines the fixed executable - harder to override. Use both together: ENTRYPOINT for the process, CMD for its default arguments.

How do you check what a running container is doing?

Use docker logs -f CONTAINER_ID for live log output and docker stats for real-time CPU and memory usage. For deeper inspection - mounts, env vars, network config - run docker inspect CONTAINER_ID.

What is the difference between a Docker image and a Docker container?

An image is a read-only template. A container is a running instance of that image. One image can spin up dozens of containers simultaneously. Where Docker images are stored depends on your storage driver and OS.

How do you pass environment variables to a Docker container?

Use -e VAR=value in docker run, or define them under environment: in your docker-compose.yml. For multiple variables, an .env file with env_file: keeps things cleaner and keeps secrets out of version control.

How do you make container data persist after a restart?

Use named volumes or bind mounts. Without them, all data written inside the container is lost when it stops. Mount a volume with -v myvolume:/app/data in docker run, or declare it under volumes: in Compose.

What does docker system prune do?

It removes stopped containers, dangling images, unused networks, and the build cache. Add -a to also delete unused tagged images. Add --volumes to include Docker volumes. Significant disk space recovery on active dev machines.

When should you use Docker Compose instead of plain docker run?

Any time you have more than one container. Docker Compose defines your full stack - app, database, cache - in one YAML file, with shared networks and volumes wired up automatically. Far easier to manage than multiple docker run commands.