Complete reference for the Docker command-line interface, covering container lifecycle, image management, networking, builds, and diagnostics.

Table of Contents#

  1. Overview
  2. Installation
  3. Container Operations
  4. Image Management
  5. Building Images
  6. Volume Management
  7. Networking
  8. Resource Constraints
  9. Backup and Restore
  10. Troubleshooting

1. Overview#

Docker is a platform for building, shipping, and running applications in isolated containers using OS-level virtualization. The Docker CLI (docker) is the primary interface for interacting with the Docker daemon.

Key concepts:

ConceptDescription
ImageRead-only template containing application code, runtime, libraries, and configuration
ContainerRunnable instance of an image with its own writable filesystem layer
VolumePersistent storage mechanism decoupled from container lifecycle
NetworkVirtual network enabling communication between containers and the host
RegistryStorage and distribution service for images (e.g., Docker Hub, GHCR)

2. Installation#

2.1 Package Manager Installation#

# Arch Linux
pacman -S docker

# Debian / Ubuntu (official repo recommended)
sudo apt update
sudo apt install ca-certificates curl gnupg
sudo install -m 0755 -d /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg
echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu $(. /etc/os-release && echo "$VERSION_CODENAME") stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
sudo apt update
sudo apt install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin

# RHEL / Fedora
sudo dnf config-manager --add-repo https://download.docker.com/linux/fedora/docker-ce.repo
sudo dnf install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin

2.2 Convenience Script#

curl -fsSL https://get.docker.com -o get-docker.sh
sudo sh get-docker.sh

Note: The convenience script is not recommended for production. It does not allow customization and always installs the latest version.

2.3 Post-Installation Setup#

Run Docker as a non-root user by adding yourself to the docker group:

sudo groupadd docker
sudo usermod -aG docker $USER
newgrp docker

Enable and start the Docker daemon:

sudo systemctl enable --now docker.service

Verify the installation:

docker run --rm hello-world

3. Container Operations#

3.1 Running Containers#

CommandDescription
docker run <image>Create and start a new container
docker run --name <name> <image>Run with a specific container name
docker run -d <image>Run in detached (background) mode
docker run -it <image> /bin/shRun interactively with a terminal
docker run -p <host>:<container> <image>Map a host port to a container port
docker run -P <image>Map all exposed ports to random host ports
docker run -v <host_path>:<container_path> <image>Bind-mount a host directory
docker run --mount type=volume,src=<vol>,dst=<path> <image>Mount a named volume
docker run -e <VAR>=<value> <image>Set an environment variable
docker run --env-file <file> <image>Load environment variables from a file
docker run --rm <image>Automatically remove the container on exit
docker run --restart=unless-stopped <image>Set restart policy
docker run --network <network> <image>Connect to a specific network

3.2 Container Lifecycle#

CommandDescription
docker create <image>Create a container without starting it
docker start <container>Start a stopped container
docker stop <container>Gracefully stop a container (SIGTERM, then SIGKILL after timeout)
docker kill <container>Immediately kill a container (SIGKILL)
docker restart <container>Stop and restart a container
docker pause <container>Suspend all processes in a container
docker unpause <container>Resume a paused container
docker rm <container>Remove a stopped container
docker rm -f <container>Force-remove a running container
docker rename <old> <new>Rename a container
docker update --restart=always <container>Update container configuration live

3.3 Inspecting Containers#

CommandDescription
docker psList running containers
docker ps -aList all containers (including stopped)
docker ps -sShow container sizes
docker logs <container>Show container stdout/stderr
docker logs -f --tail 100 <container>Follow logs, starting from last 100 lines
docker logs --since 1h <container>Show logs from the last hour
docker top <container>List processes in a container
docker statsLive resource usage for all running containers
docker stats <container>Live resource usage for a specific container
docker diff <container>Show filesystem changes vs. the image
docker inspect <container>Show detailed container metadata (JSON)
docker inspect -f '{{.NetworkSettings.IPAddress}}' <container>Extract a single field with Go templates
docker port <container>Show port mappings

3.4 Executing Commands#

CommandDescription
docker exec <container> <command>Run a command in a running container
docker exec -it <container> /bin/bashOpen an interactive shell (use /bin/sh if bash is unavailable)
docker exec -u root <container> <command>Run as a specific user
docker attach <container>Attach to the main process (Ctrl+P, Ctrl+Q to detach)
docker cp <container>:<path> <host_path>Copy files from container to host
docker cp <host_path> <container>:<path>Copy files from host to container
docker export <container> > backup.tarExport container filesystem as tar
docker wait <container>Block until container stops, then print exit code

3.5 Bulk Operations#

CommandDescription
docker stop $(docker ps -q)Stop all running containers
docker rm $(docker ps -aq)Remove all stopped containers
docker rm -vf $(docker ps -aq)Force-remove all containers and their anonymous volumes
docker rmi $(docker images -q)Remove all images
docker rmi $(docker images -f dangling=true -q)Remove dangling (untagged) images
docker system pruneRemove unused containers, networks, and dangling images
docker system prune -a --volumesRemove all unused data including volumes and all unused images
docker system dfShow Docker disk usage

4. Image Management#

4.1 Image Commands#

CommandDescription
docker imagesList local images
docker images -aList all images (including intermediate layers)
docker pull <repo>:<tag>Pull an image from a registry
docker push <repo>:<tag>Push an image to a registry
docker tag <image> <repo>:<tag>Tag an image
docker build -t <repo>:<tag> .Build an image from a Dockerfile
docker history <image>Show image layer history
docker inspect <image>Show image metadata (JSON)
docker rmi <image>Remove an image
docker save <image> -o image.tarExport an image as a tarball
docker load -i image.tarImport an image from a tarball
docker commit <container> <image>Create an image from a container
docker import <url_or_file>Create an image from a tarball or URL
docker search <term>Search Docker Hub for images
docker login <registry>Log in to a registry
docker logout <registry>Log out from a registry

4.2 Content Trust and Signing#

Docker Content Trust (DCT) uses digital signatures to verify image integrity and publisher authenticity.

# Enable content trust globally
export DOCKER_CONTENT_TRUST=1

# Pull only signed images (with DCT enabled)
docker pull <repo>:<tag>

# Push and sign an image
docker push <repo>:<tag>

# Inspect signing data
docker trust inspect <repo>:<tag>

# Sign an existing image
docker trust sign <repo>:<tag>

# Revoke trust for a tag
docker trust revoke <repo>:<tag>

# Disable content trust for a single command
DOCKER_CONTENT_TRUST=0 docker pull <repo>:<tag>

Key points:

  • DCT keys are stored in ~/.docker/trust/
  • Root keys should be kept offline and backed up securely
  • Repository keys are generated per-repo on first signed push
  • Notary server handles the trust metadata (Docker Hub uses built-in Notary)

5. Building Images#

5.1 Docker Build#

# Basic build
docker build -t <repo>:<tag> .

# Build with a specific Dockerfile
docker build -f Dockerfile.prod -t <repo>:<tag> .

# Build with build arguments
docker build --build-arg VERSION=1.0 -t <repo>:<tag> .

# Build without cache
docker build --no-cache -t <repo>:<tag> .

# Build with target stage (multi-stage)
docker build --target builder -t <repo>:<tag> .

# Build with secret (BuildKit)
DOCKER_BUILDKIT=1 docker build --secret id=mysecret,src=secret.txt -t <repo>:<tag> .

# Build with SSH forwarding (BuildKit)
DOCKER_BUILDKIT=1 docker build --ssh default -t <repo>:<tag> .

5.2 Docker Buildx (Multi-Platform)#

Buildx extends docker build with BuildKit features including multi-platform image creation.

# Install buildx (included with Docker Desktop; on Linux, install the plugin)
docker buildx version

# Create a new builder with multi-platform support
docker buildx create --name multiplatform --driver docker-container --use

# Bootstrap the builder
docker buildx inspect --bootstrap

# Build for multiple platforms and push to a registry
docker buildx build --platform linux/amd64,linux/arm64,linux/arm/v7 \
  -t <repo>:<tag> --push .

# Build for a single foreign platform (load into local daemon)
docker buildx build --platform linux/arm64 -t <repo>:<tag> --load .

# Build with cache export/import (speeds up CI pipelines)
docker buildx build --cache-from type=registry,ref=<repo>:cache \
  --cache-to type=registry,ref=<repo>:cache,mode=max \
  -t <repo>:<tag> --push .

# List builders
docker buildx ls

# Remove a builder
docker buildx rm multiplatform

Platform strings follow the format <os>/<arch>/<variant>. Common targets:

PlatformDescription
linux/amd64Standard x86_64
linux/arm6464-bit ARM (Raspberry Pi 4+, AWS Graviton)
linux/arm/v732-bit ARM (Raspberry Pi 2/3)
linux/arm/v6Older ARM (Raspberry Pi Zero)
linux/38632-bit x86
linux/s390xIBM Z mainframe
linux/ppc64leIBM POWER

6. Volume Management#

CommandDescription
docker volume lsList all volumes
docker volume create <volume>Create a named volume
docker volume inspect <volume>Show volume metadata (JSON)
docker volume rm <volume>Remove a volume
docker volume ls -f dangling=trueList volumes not referenced by any container
docker volume pruneRemove all unused volumes

Volume types:

TypeSyntaxUse Case
Named volume-v mydata:/dataPersistent data managed by Docker
Bind mount-v /host/path:/container/pathShare host files with containers
tmpfs mount--tmpfs /tmpIn-memory storage, not persisted
Named volume (explicit)--mount type=volume,src=mydata,dst=/dataSame as -v but more explicit

Volume data is stored in /var/lib/docker/volumes/ by default.

7. Networking#

7.1 Network Drivers#

Docker provides several built-in network drivers:

DriverDescriptionUse Case
bridgeDefault; isolated network on the host with NATSingle-host container communication
hostContainer shares the host's network namespaceMaximum network performance, no isolation
noneNo networkingCompletely isolated containers
overlayMulti-host networking via VXLANDocker Swarm services across nodes
macvlanAssigns a MAC address, container appears as a physical device on the LANLegacy apps that need direct L2 access
ipvlanSimilar to macvlan but shares the host MACEnvironments where MAC limits are a concern

7.2 Network Commands#

CommandDescription
docker network lsList all networks
docker network create <network>Create a bridge network
docker network create -d overlay <network>Create an overlay network
docker network create --subnet=172.20.0.0/16 <network>Create a network with a specific subnet
docker network create --driver macvlan --subnet=192.168.1.0/24 --gateway=192.168.1.1 -o parent=eth0 <network>Create a macvlan network
docker network inspect <network>Show network details (JSON)
docker network connect <network> <container>Attach a running container to a network
docker network disconnect <network> <container>Detach a container from a network
docker network rm <network>Remove a network
docker network pruneRemove all unused networks

7.3 DNS and Service Discovery#

Containers on user-defined networks (not the default bridge) get automatic DNS resolution by container name:

# Create a user-defined bridge
docker network create mynet

# Start two containers on the same network
docker run -d --name web --network mynet nginx
docker run -d --name app --network mynet myapp

# 'app' can reach 'web' by name
docker exec app ping web

Key DNS behavior:

  • Default bridge network: no automatic DNS; use --link (legacy) or switch to user-defined networks
  • User-defined bridge: embedded DNS server at 127.0.0.11 resolves container names
  • Custom DNS: use --dns <ip> to specify external DNS servers
  • DNS search domains: use --dns-search <domain>
  • Aliases: --network-alias <alias> adds additional DNS names for a container

7.4 Connecting Containers#

# Run a container with a specific IP on a custom network
docker network create --subnet=172.20.0.0/16 mynet
docker run -d --name db --network mynet --ip 172.20.0.10 postgres

# Connect a running container to an additional network
docker network connect mynet existing-container

# Expose ports to the host
docker run -d -p 8080:80 nginx              # Map host 8080 to container 80
docker run -d -p 127.0.0.1:8080:80 nginx    # Bind to localhost only
docker run -d -p 8080:80/udp nginx           # UDP port mapping

# Publish a range of ports
docker run -d -p 8000-8010:8000-8010 myapp

# Container-to-container without publishing ports
# (containers on the same user-defined network can communicate on any port)

8. Resource Constraints#

Limit CPU, memory, and other resources to prevent a single container from consuming all host resources.

Memory Constraints#

# Hard memory limit (container is killed if exceeded)
docker run -d --memory=512m <image>

# Memory + swap limit (total; set equal to --memory to disable swap)
docker run -d --memory=512m --memory-swap=512m <image>

# Soft limit (reservation, used for scheduling decisions)
docker run -d --memory=512m --memory-reservation=256m <image>

# Kernel memory limit
docker run -d --memory=512m --kernel-memory=50m <image>

# OOM kill disable (use with caution)
docker run -d --memory=512m --oom-kill-disable <image>

CPU Constraints#

# Limit to specific number of CPUs
docker run -d --cpus=1.5 <image>

# CPU shares (relative weight, default 1024)
docker run -d --cpu-shares=512 <image>

# Pin to specific CPU cores
docker run -d --cpuset-cpus="0,2" <image>

# CPU period and quota (fine-grained control)
docker run -d --cpu-period=100000 --cpu-quota=50000 <image>

Other Constraints#

# Limit block I/O weight (10-1000, default 500)
docker run -d --blkio-weight=300 <image>

# Limit read/write bandwidth
docker run -d --device-read-bps /dev/sda:10mb --device-write-bps /dev/sda:10mb <image>

# Limit number of PIDs
docker run -d --pids-limit=100 <image>

# Set ulimits
docker run -d --ulimit nofile=1024:2048 --ulimit nproc=512 <image>

# GPU access (requires NVIDIA Container Toolkit)
docker run -d --gpus all <image>
docker run -d --gpus '"device=0,1"' <image>

Viewing Resource Usage#

# Live stats for all containers
docker stats

# One-shot stats (no streaming)
docker stats --no-stream

# Format output
docker stats --format "table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}"

# Check resource limits on a running container
docker inspect -f '{{.HostConfig.Memory}}' <container>

9. Backup and Restore#

Backing Up Container Volumes#

# Backup a named volume to a tar archive
docker run --rm -v <volume_name>:/source -v $(pwd):/backup busybox \
  tar czf /backup/backup.tar.gz -C /source .

# Backup using --volumes-from (copies all volumes from a container)
docker run --rm --volumes-from <container> -v $(pwd):/backup busybox \
  tar czf /backup/backup.tar.gz <container_path>

Restoring from Backup#

# Restore a named volume from a tar archive
docker run --rm -v <volume_name>:/target -v $(pwd):/backup busybox \
  sh -c "cd /target && tar xzf /backup/backup.tar.gz"

Backing Up Images#

# Save one or more images to a tar archive
docker save -o images.tar <image1>:<tag> <image2>:<tag>

# Load images from a tar archive
docker load -i images.tar

10. Troubleshooting#

IssueCauseSolution
Cannot connect to the Docker daemonDocker service not runningsudo systemctl start docker
permission denied on docker commandsUser not in docker groupsudo usermod -aG docker $USER then log out/in
Container exits immediatelyMain process crashes or finishesCheck docker logs <container> for errors
Port already in useAnother process binds the same host portss -tlnp | grep <port> to find the conflict
DNS resolution fails in containerDefault bridge network has no embedded DNSUse a user-defined network: docker network create mynet
Container cannot reach the internetiptables or firewall blocking Docker NATCheck iptables -L -n -t nat and ensure IP forwarding is enabled: sysctl net.ipv4.ip_forward
no space left on deviceDocker storage pool fulldocker system prune -a --volumes and check /var/lib/docker usage
Slow buildsNo layer cache reuseOrder Dockerfile instructions from least to most frequently changed
Container has no networkStarted with --network none or network was deletedReconnect: docker network connect <network> <container>
Inter-container name resolution failsContainers on default bridgeMove both containers to a user-defined bridge network
OOM killed containerExceeded memory limitIncrease --memory or optimize application memory usage
network <name> not foundNetwork was pruned or never createddocker network create <name>

Network Diagnostic Tools#

# Run netshoot for comprehensive network debugging
docker run --rm -it --network container:<target_container> nicolaka/netshoot

# Test DNS resolution inside a container
docker exec <container> nslookup <hostname>

# Check container network configuration
docker exec <container> ip addr
docker exec <container> ip route

# Inspect bridge network details
docker network inspect bridge

# Capture traffic on a container's network
docker run --rm -it --net container:<target_container> nicolaka/netshoot tcpdump -i eth0

# Test connectivity between containers
docker exec <container_a> ping <container_b>

See Also#

Sources#