Top Tags

Docker CLI Handbook

Quick reference for essential Docker commands — container lifecycle, image management, volumes, networks, Docker Compose, logs, debugging, and more.

Installation & Setup

Install Docker Engine

bash
1# Ubuntu / Debian
2sudo apt update
3sudo apt install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
4
5# Fedora
6sudo dnf install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
7
8# macOS (Homebrew cask)
9brew install --cask docker
10
11# Verify installation
12docker --version
13docker compose version

Post-Install (Linux — Run Docker Without sudo)

bash
1sudo groupadd docker
2sudo usermod -aG docker $USER
3newgrp docker # Apply group membership without logout
4docker run hello-world # Test without sudo

Shell Autocomplete

bash
1# Bash
2mkdir -p ~/.local/share/bash-completion/completions
3docker completion bash > ~/.local/share/bash-completion/completions/docker
4
5# Zsh
6mkdir -p ~/.docker/completions
7docker completion zsh > ~/.docker/completions/_docker
8echo 'fpath=(~/.docker/completions $fpath)' >> ~/.zshrc
9echo 'autoload -Uz compinit && compinit' >> ~/.zshrc
10
11# Fish
12mkdir -p ~/.config/fish/completions
13docker completion fish > ~/.config/fish/completions/docker.fish

Useful Aliases

bash
1alias d=docker
2alias dc='docker compose'
3alias dps='docker ps'
4alias dpsa='docker ps -a'
5alias di='docker images'
6alias dex='docker exec -it'
7alias dlogs='docker logs -f'
8alias drm='docker rm'
9alias drmi='docker rmi'

Important Paths & Config Files

Docker Daemon Configuration

Linux

bash
1/etc/docker/daemon.json # Daemon config (create if missing)
2~/.docker/config.json # Client config (auth, proxies, plugins)
3~/.docker/ # Client config directory

macOS (Docker Desktop)

bash
1~/.docker/daemon.json # Daemon config (also editable via Docker Desktop → Settings → Docker Engine)
2~/.docker/config.json # Client config (auth, proxies, plugins)
3~/Library/Group Containers/group.com.docker/settings-store.json # Docker Desktop settings
4~/Library/Containers/com.docker.docker/Data/ # Docker Desktop application data

Data & Storage Paths

Linux

bash
1/var/lib/docker/ # Docker root directory (images, containers, volumes)
2/var/lib/docker/containers/ # Container metadata and per-container logs
3/var/lib/docker/image/ # Image layer metadata
4/var/lib/docker/volumes/ # Named volumes data
5/var/lib/docker/overlay2/ # OverlayFS storage driver layers (default)
6/var/lib/docker/network/ # Network configuration files
7/var/lib/docker/buildkit/ # BuildKit build cache
8/var/lib/docker/tmp/ # Temporary files during builds/pulls

macOS (Docker Desktop)

bash
1# Docker Desktop runs a Linux VM — data is stored inside the VM's virtual disk:
2~/Library/Containers/com.docker.docker/Data/vms/0/data/ # VM virtual disk image
3# Named volumes, images, containers are all inside this VM disk.
4# You access them via Docker CLI, not filesystem paths.
5
6# Docker Desktop disk image location:
7~/Library/Containers/com.docker.docker/Data/vms/0/data/Docker.raw # Raw disk format (default)

Log Locations

Linux

bash
1# Container logs (json-file driver — default)
2/var/lib/docker/containers/<container-id>/<container-id>-json.log
3
4# Docker daemon logs
5journalctl -xu docker.service # systemd (Ubuntu 16.04+, Fedora, RHEL 7+)
6/var/log/syslog # Debian / Ubuntu (fallback / non-systemd)
7/var/log/messages # RHEL / Fedora / CentOS (fallback / non-systemd)

macOS (Docker Desktop)

bash
1# Docker daemon logs
2~/Library/Containers/com.docker.docker/Data/log/vm/dockerd.log
3
4# Containerd logs
5~/Library/Containers/com.docker.docker/Data/log/vm/containerd.log
6
7# Docker Desktop application logs
8~/Library/Containers/com.docker.docker/Data/log/host/
9
10# Container logs — access via CLI only:
11docker logs <container> # Container logs live inside the Linux VM

Environment Variables

bash
1DOCKER_HOST=tcp://192.168.1.10:2376 # Connect to remote Docker daemon
2DOCKER_HOST=unix:///var/run/docker.sock # Default socket (Linux)
3DOCKER_HOST=unix://$HOME/.docker/run/docker.sock # Default socket (macOS Docker Desktop)
4DOCKER_TLS_VERIFY=1 # Enable TLS verification
5DOCKER_CERT_PATH=~/.docker/certs # Path to TLS certificates
6DOCKER_CONFIG=~/.docker # Client config directory
7DOCKER_BUILDKIT=1 # Enable BuildKit (default in modern Docker)
8COMPOSE_FILE=compose.yaml # Compose file path
9COMPOSE_PROJECT_NAME=myproject # Override project name

System & Info

Docker System Commands

bash
1docker version # Client and server version details
2docker info # System-wide information (containers, images, storage)
3docker system df # Show disk usage by Docker objects
4docker system df -v # Verbose disk usage (per image/container/volume)
5docker system events # Real-time events from daemon
6docker system events --since=1h # Events from the last hour
7docker system prune # Remove all unused data (containers, networks, images)
8docker system prune -a # Also remove unused images (not just dangling)
9docker system prune -a --volumes # Remove everything including volumes

Container Lifecycle

Run Containers

bash
1docker run nginx # Run container (foreground)
2docker run -d nginx # Run in detached (background) mode
3docker run -d --name my-nginx nginx # Run with custom name
4docker run -d -p 8080:80 nginx # Map host port 8080 → container port 80
5docker run -d -p 127.0.0.1:8080:80 nginx # Bind to specific host interface
6docker run -d -P nginx # Map all exposed ports to random host ports
7docker run -it ubuntu /bin/bash # Interactive shell
8docker run --rm alpine echo "hello" # Remove container after exit
9docker run -d --restart=unless-stopped nginx # Restart policy
10docker run -d -e MY_VAR=value nginx # Set environment variable
11docker run -d --env-file .env nginx # Load env vars from file
12docker run -d -v mydata:/data nginx # Mount named volume
13docker run -d -v $(pwd):/app nginx # Bind mount current directory
14docker run -d --network my-net nginx # Connect to specific network
15docker run --memory=512m --cpus=1.5 nginx # Set resource limits
16docker run -d -w /app node:20 npm start # Set working directory
17docker run -d --user 1000:1000 nginx # Run as specific user/group
18docker run -d --read-only nginx # Read-only root filesystem
19docker run -d --pid=host nginx # Share host PID namespace

List Containers

bash
1docker ps # List running containers
2docker ps -a # List all containers (including stopped)
3docker ps -q # List only container IDs
4docker ps -aq # All container IDs (useful for batch operations)
5docker ps -s # Show container sizes
6docker ps -l # Show last created container
7docker ps --format "table {{.ID}}\t{{.Names}}\t{{.Status}}\t{{.Ports}}" # Custom format
8docker ps -f status=exited # Filter by status
9docker ps -f name=my-app # Filter by name
10docker ps -f ancestor=nginx # Filter by image
11docker container ls # Same as docker ps

Start / Stop / Restart

bash
1docker start my-container # Start a stopped container
2docker start -ai my-container # Start and attach with interactive TTY
3docker stop my-container # Graceful stop (SIGTERM → SIGKILL after 10s)
4docker stop -t 30 my-container # Custom grace period (30 seconds)
5docker restart my-container # Restart container
6docker pause my-container # Pause all processes (freeze)
7docker unpause my-container # Unpause container
8docker kill my-container # Force stop (SIGKILL)
9docker kill -s SIGHUP my-container # Send specific signal
10docker wait my-container # Block until container stops, print exit code

Remove Containers

bash
1docker rm my-container # Remove a stopped container
2docker rm -f my-container # Force remove (even if running)
3docker rm -v my-container # Remove with associated anonymous volumes
4docker rm $(docker ps -aq) # Remove all stopped containers
5docker rm $(docker ps -aq -f status=exited) # Remove all exited containers
6docker container prune # Remove all stopped containers
7docker container prune -f # Remove without confirmation

Execute Commands in Running Containers

bash
1docker exec my-container ls / # Run command in container
2docker exec -it my-container /bin/sh # Interactive shell
3docker exec -it my-container /bin/bash # Interactive bash
4docker exec -it -u root my-container sh # Exec as root
5docker exec -e MY_VAR=value my-container env # With environment variable
6docker exec -w /app my-container pwd # With working directory

Inspect Containers

bash
1docker inspect my-container # Full container details (JSON)
2docker inspect -f '{{.State.Status}}' my-container # Get specific field
3docker inspect -f '{{.NetworkSettings.IPAddress}}' my-container # Get container IP
4docker inspect -f '{{.HostConfig.RestartPolicy.Name}}' my-container # Get restart policy
5docker inspect -f '{{json .Mounts}}' my-container # Volume mounts (JSON)
6docker stats # Live resource usage (CPU, memory, I/O)
7docker stats --no-stream # One-time snapshot of stats
8docker stats my-container # Stats for specific container
9docker top my-container # Running processes inside container
10docker diff my-container # Changed files in container filesystem
11docker port my-container # Show port mappings

Copy Files

bash
1docker cp file.txt my-container:/tmp/file.txt # Host → Container
2docker cp my-container:/tmp/file.txt ./file.txt # Container → Host
3docker cp my-container:/var/log/ ./logs/ # Copy directory

Image Management

List & Search Images

bash
1docker images # List local images
2docker images -a # Include intermediate images
3docker images -q # IDs only
4docker images --digests # Show digests
5docker images --format "table {{.Repository}}\t{{.Tag}}\t{{.Size}}" # Custom format
6docker images --filter dangling=true # Show dangling images
7docker images --filter reference=nginx # Filter by name
8docker search nginx # Search Docker Hub
9docker search --limit 5 nginx # Limit search results
10docker search --filter is-official=true nginx # Official images only

Pull & Push Images

bash
1docker pull nginx # Pull latest tag
2docker pull nginx:1.27 # Pull specific tag
3docker pull nginx:1.27@sha256:abc... # Pull by digest
4docker pull --all-tags nginx # Pull all tags
5docker push myuser/myimage:latest # Push to registry
6docker push myuser/myimage:v1.0 # Push specific tag

Build Images

bash
1docker build -t myapp:latest . # Build from Dockerfile in current dir
2docker build -t myapp:v1.0 -f Dockerfile.prod . # Use specific Dockerfile
3docker build --no-cache -t myapp . # Build without cache
4docker build --build-arg VERSION=1.0 -t myapp . # Pass build argument
5docker build --target builder -t myapp . # Multi-stage: build specific target
6docker build --platform linux/amd64 -t myapp . # Build for specific platform
7docker buildx build --push -t myuser/myapp . # Build and push (BuildKit)
8docker buildx build --platform linux/amd64,linux/arm64 -t myuser/myapp --push . # Multi-arch

Tag & Remove Images

bash
1docker tag myapp:latest myuser/myapp:v1.0 # Tag an image
2docker tag myapp:latest registry.example.com/myapp:v1.0 # Tag for private registry
3docker rmi myapp:latest # Remove an image
4docker rmi $(docker images -q) # Remove all images
5docker rmi $(docker images -f dangling=true -q) # Remove dangling images
6docker image prune # Remove dangling images
7docker image prune -a # Remove all unused images

Save & Load Images (Offline Transfer)

bash
1docker save -o myapp.tar myapp:latest # Export image to tar file
2docker save myapp:latest | gzip > myapp.tar.gz # Export compressed
3docker load -i myapp.tar # Import image from tar file
4docker load < myapp.tar.gz # Import compressed
5docker export my-container > container.tar # Export container filesystem
6docker import container.tar myimage:latest # Import as image

Image History & Layers

bash
1docker history myapp:latest # Show image layers and commands
2docker history --no-trunc myapp # Full command output (not truncated)
3docker manifest inspect nginx:latest # Inspect image manifest (multi-arch info)

Volumes

Manage Volumes

bash
1docker volume create mydata # Create a named volume
2docker volume ls # List all volumes
3docker volume inspect mydata # Show volume details (mountpoint, driver)
4docker volume rm mydata # Remove a volume
5docker volume rm $(docker volume ls -q) # Remove all volumes
6docker volume prune # Remove all unused volumes
7docker volume prune -f # Remove without confirmation

Using Volumes with Containers

bash
1# Named volume
2docker run -d -v mydata:/var/lib/data postgres
3
4# Bind mount (host directory)
5docker run -d -v /host/path:/container/path nginx
6
7# Read-only mount
8docker run -d -v mydata:/data:ro nginx
9
10# tmpfs mount (in-memory, Linux only)
11docker run -d --tmpfs /tmp:rw,size=100m nginx
12
13# Mount syntax (modern — preferred)
14docker run -d --mount source=mydata,target=/data nginx
15docker run -d --mount type=bind,source=$(pwd),target=/app nginx
16docker run -d --mount type=tmpfs,target=/tmp,tmpfs-size=100m nginx

Networks

Manage Networks

bash
1docker network create my-net # Create bridge network (default driver)
2docker network create --driver bridge my-net # Explicit bridge driver
3docker network create --driver overlay my-net # Overlay network (Swarm)
4docker network create --subnet=172.20.0.0/16 my-net # Custom subnet
5docker network ls # List all networks
6docker network inspect my-net # Show network details
7docker network rm my-net # Remove a network
8docker network prune # Remove all unused networks

Connect & Disconnect Containers

bash
1docker network connect my-net my-container # Add container to network
2docker network disconnect my-net my-container # Remove container from network
3
4# Run container on specific network
5docker run -d --network my-net --name app1 nginx
6
7# Container DNS — containers on same user-defined network resolve each other by name
8docker run -d --network my-net --name db postgres
9docker run -d --network my-net --name app nginx
10# Inside "app": ping db → resolves to the db container's IP

Default Network Drivers

DriverDescription
bridgeDefault. Isolated network on a single host
hostContainer shares host network (no isolation)
noneNo networking
overlayMulti-host networking (Docker Swarm)
macvlanAssign MAC address, appear as physical device

Logs & Debugging

Container Logs

bash
1docker logs my-container # Show all logs (stdout + stderr)
2docker logs -f my-container # Follow/stream logs
3docker logs --tail 100 my-container # Last 100 lines
4docker logs --since 1h my-container # Logs from last hour
5docker logs --since 30m my-container # Logs from last 30 minutes
6docker logs --until 2h my-container # Logs up to 2 hours ago
7docker logs -t my-container # Show timestamps
8docker logs --details my-container # Show extra attributes (log tags)
9docker logs my-container 2>&1 | grep "error" # Filter logs with grep

Debugging Containers

bash
1# Inspect container state
2docker inspect my-container
3docker inspect -f '{{.State.ExitCode}}' my-container # Check exit code
4docker inspect -f '{{.State.OOMKilled}}' my-container # Check if OOM killed
5
6# Check events
7docker events # Real-time events from daemon
8docker events --filter container=my-container # Events for specific container
9docker events --filter type=container # Container events only
10docker events --filter event=die # Only "die" events
11
12# Resource usage
13docker stats # Live CPU, memory, I/O for all containers
14docker top my-container # Show running processes
15docker diff my-container # Show filesystem changes
16
17# Debug with temporary container
18docker run --rm -it --network container:my-container nicolaka/netshoot # Network debugging
19docker run --rm -it --pid container:my-container busybox ps aux # Process debugging

Troubleshooting Checklist

bash
1# Container won't start?
2docker logs my-container # Check application logs
3docker inspect my-container # Check State.Error and State.ExitCode
4
5# Container keeps restarting?
6docker inspect -f '{{.RestartCount}}' my-container # Check restart count
7docker logs --tail 50 my-container # Check recent logs
8
9# Can't connect to container?
10docker port my-container # Verify port mappings
11docker inspect -f '{{.NetworkSettings.IPAddress}}' my-container # Get container IP
12docker network inspect bridge # Check network config
13
14# Disk space issues?
15docker system df # Check Docker disk usage
16docker system prune -a --volumes # Clean up everything unused
17
18# Docker daemon issues?
19journalctl -xu docker.service # Check daemon logs (Linux)
20sudo systemctl status docker # Check daemon status
21sudo systemctl restart docker # Restart daemon

Docker Compose

Basic Commands

bash
1docker compose up # Start all services (foreground)
2docker compose up -d # Start in detached mode
3docker compose up -d --build # Build images before starting
4docker compose up -d --force-recreate # Recreate containers even if unchanged
5docker compose up -d --no-deps web # Start specific service without dependencies
6docker compose down # Stop and remove containers, networks
7docker compose down -v # Also remove volumes
8docker compose down --rmi all # Also remove images
9docker compose stop # Stop services (don't remove)
10docker compose start # Start stopped services
11docker compose restart # Restart all services
12docker compose restart web # Restart specific service

Build & Images

bash
1docker compose build # Build all services
2docker compose build web # Build specific service
3docker compose build --no-cache # Build without cache
4docker compose pull # Pull all service images
5docker compose push # Push all service images

Status & Logs

bash
1docker compose ps # List running services
2docker compose ps -a # List all services (including stopped)
3docker compose logs # View logs from all services
4docker compose logs -f # Follow logs
5docker compose logs web # Logs for specific service
6docker compose logs --tail 50 web # Last 50 lines
7docker compose logs --since 1h # Logs from last hour
8docker compose top # Show running processes

Execute & Run

bash
1docker compose exec web sh # Shell into running service
2docker compose exec web bash # Bash into running service
3docker compose exec -u root web sh # Shell as root
4docker compose run web npm test # Run one-off command in new container
5docker compose run --rm web npm test # Run and remove after

Scaling & Config

bash
1docker compose up -d --scale web=3 # Scale service to 3 instances
2docker compose config # Validate and show resolved config
3docker compose config --services # List service names
4docker compose config --volumes # List volume names
5docker compose convert # Convert compose file to canonical format

Compose File Reference

bash
1docker compose -f compose.prod.yaml up -d # Use specific compose file
2docker compose -f compose.yaml -f compose.override.yaml up -d # Merge multiple files
3docker compose --env-file .env.prod up -d # Use specific env file
4docker compose -p myproject up -d # Set project name

Docker Registry & Login

Authentication

bash
1docker login # Login to Docker Hub (interactive)
2docker login -u myuser # Login with username
3docker login registry.example.com # Login to private registry
4docker logout # Logout from Docker Hub
5docker logout registry.example.com # Logout from private registry

Working with Registries

bash
1# Docker Hub
2docker pull nginx:latest
3docker push myuser/myapp:v1.0
4
5# Private registry
6docker pull registry.example.com/myapp:latest
7docker push registry.example.com/myapp:latest
8
9# Run a local registry
10docker run -d -p 5000:5000 --name registry registry:2
11docker tag myapp localhost:5000/myapp:latest
12docker push localhost:5000/myapp:latest

Dockerfile Quick Reference

Common Instructions

InstructionDescription
FROMBase image
WORKDIRSet working directory
COPYCopy files from host to image
ADDCopy files (supports URLs and tar extraction)
RUNExecute command during build
CMDDefault command when container starts
ENTRYPOINTMain executable (CMD becomes arguments)
ENVSet environment variable
ARGBuild-time variable
EXPOSEDocument which ports the container listens on
VOLUMECreate mount point for volumes
USERSet user for subsequent instructions
LABELAdd metadata to image
HEALTHCHECKDefine health check command
.dockerignoreExclude files from build context

Example Multi-Stage Dockerfile

dockerfile
1# Build stage
2FROM node:20-alpine AS builder
3WORKDIR /app
4COPY package*.json ./
5RUN npm ci
6COPY . .
7RUN npm run build
8
9# Production stage
10FROM node:20-alpine
11WORKDIR /app
12COPY --from=builder /app/dist ./dist
13COPY --from=builder /app/node_modules ./node_modules
14EXPOSE 3000
15USER node
16CMD ["node", "dist/index.js"]

Cleanup & Maintenance

Prune Commands

bash
1docker container prune # Remove stopped containers
2docker image prune # Remove dangling images
3docker image prune -a # Remove all unused images
4docker volume prune # Remove unused volumes
5docker network prune # Remove unused networks
6docker builder prune # Remove BuildKit cache
7docker system prune # Remove all unused objects
8docker system prune -a --volumes # Nuclear option — remove everything unused

Disk Usage

bash
1docker system df # Summary of disk usage
2docker system df -v # Detailed disk usage per object

Useful Patterns

Health Checks

bash
1# In Dockerfile
2HEALTHCHECK --interval=30s --timeout=5s --retries=3 \
3 CMD curl -f http://localhost/ || exit 1
4
5# In docker run
6docker run -d --health-cmd="curl -f http://localhost/ || exit 1" \
7 --health-interval=30s --health-timeout=5s --health-retries=3 nginx
8
9# Check health status
10docker inspect -f '{{.State.Health.Status}}' my-container

Resource Limits

bash
1docker run -d --memory=256m nginx # Memory limit
2docker run -d --memory=256m --memory-swap=512m nginx # Memory + swap
3docker run -d --cpus=1.5 nginx # CPU limit (1.5 cores)
4docker run -d --cpu-shares=512 nginx # Relative CPU weight
5docker run -d --pids-limit=100 nginx # Process count limit

Restart Policies

PolicyDescription
noNever restart (default)
on-failure[:max]Restart on non-zero exit code
alwaysAlways restart
unless-stoppedAlways restart unless manually stopped
bash
1docker run -d --restart=unless-stopped nginx
2docker update --restart=always my-container # Update running container

Output Formatting

Common Format Options

FlagDescription
--format "table ..."Table with custom columns
--format "{{json .}}"JSON output
--format "{{.ID}}"Specific field
-q / --quietIDs only
--no-truncDon't truncate output

Format Examples

bash
1# Custom container list
2docker ps --format "table {{.ID}}\t{{.Names}}\t{{.Status}}\t{{.Ports}}"
3
4# Get all container IPs
5docker inspect -f '{{.Name}} - {{.NetworkSettings.IPAddress}}' $(docker ps -q)
6
7# Image sizes sorted
8docker images --format "{{.Repository}}:{{.Tag}} {{.Size}}" | sort -k2 -h
9
10# JSON output for scripting
11docker inspect --format '{{json .Config.Env}}' my-container | jq .