Installation & Setup
Install Docker Engine
bash
1# Ubuntu / Debian2sudo apt update3sudo apt install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin4
5# Fedora6sudo dnf install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin7
8# macOS (Homebrew cask)9brew install --cask docker10
11# Verify installation12docker --version13docker compose versionPost-Install (Linux — Run Docker Without sudo)
bash
1sudo groupadd docker2sudo usermod -aG docker $USER3newgrp docker # Apply group membership without logout4docker run hello-world # Test without sudoShell Autocomplete
bash
1# Bash2mkdir -p ~/.local/share/bash-completion/completions3docker completion bash > ~/.local/share/bash-completion/completions/docker4
5# Zsh6mkdir -p ~/.docker/completions7docker completion zsh > ~/.docker/completions/_docker8echo 'fpath=(~/.docker/completions $fpath)' >> ~/.zshrc9echo 'autoload -Uz compinit && compinit' >> ~/.zshrc10
11# Fish12mkdir -p ~/.config/fish/completions13docker completion fish > ~/.config/fish/completions/docker.fishUseful Aliases
bash
1alias d=docker2alias 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 directorymacOS (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 settings4~/Library/Containers/com.docker.docker/Data/ # Docker Desktop application dataData & Storage Paths
Linux
bash
1/var/lib/docker/ # Docker root directory (images, containers, volumes)2/var/lib/docker/containers/ # Container metadata and per-container logs3/var/lib/docker/image/ # Image layer metadata4/var/lib/docker/volumes/ # Named volumes data5/var/lib/docker/overlay2/ # OverlayFS storage driver layers (default)6/var/lib/docker/network/ # Network configuration files7/var/lib/docker/buildkit/ # BuildKit build cache8/var/lib/docker/tmp/ # Temporary files during builds/pullsmacOS (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 image3# 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.log3
4# Docker daemon logs5journalctl -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 logs2~/Library/Containers/com.docker.docker/Data/log/vm/dockerd.log3
4# Containerd logs5~/Library/Containers/com.docker.docker/Data/log/vm/containerd.log6
7# Docker Desktop application logs8~/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 VMEnvironment Variables
bash
1DOCKER_HOST=tcp://192.168.1.10:2376 # Connect to remote Docker daemon2DOCKER_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 verification5DOCKER_CERT_PATH=~/.docker/certs # Path to TLS certificates6DOCKER_CONFIG=~/.docker # Client config directory7DOCKER_BUILDKIT=1 # Enable BuildKit (default in modern Docker)8COMPOSE_FILE=compose.yaml # Compose file path9COMPOSE_PROJECT_NAME=myproject # Override project nameSystem & Info
Docker System Commands
bash
1docker version # Client and server version details2docker info # System-wide information (containers, images, storage)3docker system df # Show disk usage by Docker objects4docker system df -v # Verbose disk usage (per image/container/volume)5docker system events # Real-time events from daemon6docker system events --since=1h # Events from the last hour7docker 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 volumesContainer Lifecycle
Run Containers
bash
1docker run nginx # Run container (foreground)2docker run -d nginx # Run in detached (background) mode3docker run -d --name my-nginx nginx # Run with custom name4docker run -d -p 8080:80 nginx # Map host port 8080 → container port 805docker run -d -p 127.0.0.1:8080:80 nginx # Bind to specific host interface6docker run -d -P nginx # Map all exposed ports to random host ports7docker run -it ubuntu /bin/bash # Interactive shell8docker run --rm alpine echo "hello" # Remove container after exit9docker run -d --restart=unless-stopped nginx # Restart policy10docker run -d -e MY_VAR=value nginx # Set environment variable11docker run -d --env-file .env nginx # Load env vars from file12docker run -d -v mydata:/data nginx # Mount named volume13docker run -d -v $(pwd):/app nginx # Bind mount current directory14docker run -d --network my-net nginx # Connect to specific network15docker run --memory=512m --cpus=1.5 nginx # Set resource limits16docker run -d -w /app node:20 npm start # Set working directory17docker run -d --user 1000:1000 nginx # Run as specific user/group18docker run -d --read-only nginx # Read-only root filesystem19docker run -d --pid=host nginx # Share host PID namespaceList Containers
bash
1docker ps # List running containers2docker ps -a # List all containers (including stopped)3docker ps -q # List only container IDs4docker ps -aq # All container IDs (useful for batch operations)5docker ps -s # Show container sizes6docker ps -l # Show last created container7docker ps --format "table {{.ID}}\t{{.Names}}\t{{.Status}}\t{{.Ports}}" # Custom format8docker ps -f status=exited # Filter by status9docker ps -f name=my-app # Filter by name10docker ps -f ancestor=nginx # Filter by image11docker container ls # Same as docker psStart / Stop / Restart
bash
1docker start my-container # Start a stopped container2docker start -ai my-container # Start and attach with interactive TTY3docker 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 container6docker pause my-container # Pause all processes (freeze)7docker unpause my-container # Unpause container8docker kill my-container # Force stop (SIGKILL)9docker kill -s SIGHUP my-container # Send specific signal10docker wait my-container # Block until container stops, print exit codeRemove Containers
bash
1docker rm my-container # Remove a stopped container2docker rm -f my-container # Force remove (even if running)3docker rm -v my-container # Remove with associated anonymous volumes4docker rm $(docker ps -aq) # Remove all stopped containers5docker rm $(docker ps -aq -f status=exited) # Remove all exited containers6docker container prune # Remove all stopped containers7docker container prune -f # Remove without confirmationExecute Commands in Running Containers
bash
1docker exec my-container ls / # Run command in container2docker exec -it my-container /bin/sh # Interactive shell3docker exec -it my-container /bin/bash # Interactive bash4docker exec -it -u root my-container sh # Exec as root5docker exec -e MY_VAR=value my-container env # With environment variable6docker exec -w /app my-container pwd # With working directoryInspect Containers
bash
1docker inspect my-container # Full container details (JSON)2docker inspect -f '{{.State.Status}}' my-container # Get specific field3docker inspect -f '{{.NetworkSettings.IPAddress}}' my-container # Get container IP4docker inspect -f '{{.HostConfig.RestartPolicy.Name}}' my-container # Get restart policy5docker 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 stats8docker stats my-container # Stats for specific container9docker top my-container # Running processes inside container10docker diff my-container # Changed files in container filesystem11docker port my-container # Show port mappingsCopy Files
bash
1docker cp file.txt my-container:/tmp/file.txt # Host → Container2docker cp my-container:/tmp/file.txt ./file.txt # Container → Host3docker cp my-container:/var/log/ ./logs/ # Copy directoryImage Management
List & Search Images
bash
1docker images # List local images2docker images -a # Include intermediate images3docker images -q # IDs only4docker images --digests # Show digests5docker images --format "table {{.Repository}}\t{{.Tag}}\t{{.Size}}" # Custom format6docker images --filter dangling=true # Show dangling images7docker images --filter reference=nginx # Filter by name8docker search nginx # Search Docker Hub9docker search --limit 5 nginx # Limit search results10docker search --filter is-official=true nginx # Official images onlyPull & Push Images
bash
1docker pull nginx # Pull latest tag2docker pull nginx:1.27 # Pull specific tag3docker pull nginx:1.27@sha256:abc... # Pull by digest4docker pull --all-tags nginx # Pull all tags5docker push myuser/myimage:latest # Push to registry6docker push myuser/myimage:v1.0 # Push specific tagBuild Images
bash
1docker build -t myapp:latest . # Build from Dockerfile in current dir2docker build -t myapp:v1.0 -f Dockerfile.prod . # Use specific Dockerfile3docker build --no-cache -t myapp . # Build without cache4docker build --build-arg VERSION=1.0 -t myapp . # Pass build argument5docker build --target builder -t myapp . # Multi-stage: build specific target6docker build --platform linux/amd64 -t myapp . # Build for specific platform7docker buildx build --push -t myuser/myapp . # Build and push (BuildKit)8docker buildx build --platform linux/amd64,linux/arm64 -t myuser/myapp --push . # Multi-archTag & Remove Images
bash
1docker tag myapp:latest myuser/myapp:v1.0 # Tag an image2docker tag myapp:latest registry.example.com/myapp:v1.0 # Tag for private registry3docker rmi myapp:latest # Remove an image4docker rmi $(docker images -q) # Remove all images5docker rmi $(docker images -f dangling=true -q) # Remove dangling images6docker image prune # Remove dangling images7docker image prune -a # Remove all unused imagesSave & Load Images (Offline Transfer)
bash
1docker save -o myapp.tar myapp:latest # Export image to tar file2docker save myapp:latest | gzip > myapp.tar.gz # Export compressed3docker load -i myapp.tar # Import image from tar file4docker load < myapp.tar.gz # Import compressed5docker export my-container > container.tar # Export container filesystem6docker import container.tar myimage:latest # Import as imageImage History & Layers
bash
1docker history myapp:latest # Show image layers and commands2docker 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 volume2docker volume ls # List all volumes3docker volume inspect mydata # Show volume details (mountpoint, driver)4docker volume rm mydata # Remove a volume5docker volume rm $(docker volume ls -q) # Remove all volumes6docker volume prune # Remove all unused volumes7docker volume prune -f # Remove without confirmationUsing Volumes with Containers
bash
1# Named volume2docker run -d -v mydata:/var/lib/data postgres3
4# Bind mount (host directory)5docker run -d -v /host/path:/container/path nginx6
7# Read-only mount8docker run -d -v mydata:/data:ro nginx9
10# tmpfs mount (in-memory, Linux only)11docker run -d --tmpfs /tmp:rw,size=100m nginx12
13# Mount syntax (modern — preferred)14docker run -d --mount source=mydata,target=/data nginx15docker run -d --mount type=bind,source=$(pwd),target=/app nginx16docker run -d --mount type=tmpfs,target=/tmp,tmpfs-size=100m nginxNetworks
Manage Networks
bash
1docker network create my-net # Create bridge network (default driver)2docker network create --driver bridge my-net # Explicit bridge driver3docker network create --driver overlay my-net # Overlay network (Swarm)4docker network create --subnet=172.20.0.0/16 my-net # Custom subnet5docker network ls # List all networks6docker network inspect my-net # Show network details7docker network rm my-net # Remove a network8docker network prune # Remove all unused networksConnect & Disconnect Containers
bash
1docker network connect my-net my-container # Add container to network2docker network disconnect my-net my-container # Remove container from network3
4# Run container on specific network5docker run -d --network my-net --name app1 nginx6
7# Container DNS — containers on same user-defined network resolve each other by name8docker run -d --network my-net --name db postgres9docker run -d --network my-net --name app nginx10# Inside "app": ping db → resolves to the db container's IPDefault Network Drivers
| Driver | Description |
|---|---|
bridge | Default. Isolated network on a single host |
host | Container shares host network (no isolation) |
none | No networking |
overlay | Multi-host networking (Docker Swarm) |
macvlan | Assign 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 logs3docker logs --tail 100 my-container # Last 100 lines4docker logs --since 1h my-container # Logs from last hour5docker logs --since 30m my-container # Logs from last 30 minutes6docker logs --until 2h my-container # Logs up to 2 hours ago7docker logs -t my-container # Show timestamps8docker logs --details my-container # Show extra attributes (log tags)9docker logs my-container 2>&1 | grep "error" # Filter logs with grepDebugging Containers
bash
1# Inspect container state2docker inspect my-container3docker inspect -f '{{.State.ExitCode}}' my-container # Check exit code4docker inspect -f '{{.State.OOMKilled}}' my-container # Check if OOM killed5
6# Check events7docker events # Real-time events from daemon8docker events --filter container=my-container # Events for specific container9docker events --filter type=container # Container events only10docker events --filter event=die # Only "die" events11
12# Resource usage13docker stats # Live CPU, memory, I/O for all containers14docker top my-container # Show running processes15docker diff my-container # Show filesystem changes16
17# Debug with temporary container18docker run --rm -it --network container:my-container nicolaka/netshoot # Network debugging19docker run --rm -it --pid container:my-container busybox ps aux # Process debuggingTroubleshooting Checklist
bash
1# Container won't start?2docker logs my-container # Check application logs3docker inspect my-container # Check State.Error and State.ExitCode4
5# Container keeps restarting?6docker inspect -f '{{.RestartCount}}' my-container # Check restart count7docker logs --tail 50 my-container # Check recent logs8
9# Can't connect to container?10docker port my-container # Verify port mappings11docker inspect -f '{{.NetworkSettings.IPAddress}}' my-container # Get container IP12docker network inspect bridge # Check network config13
14# Disk space issues?15docker system df # Check Docker disk usage16docker system prune -a --volumes # Clean up everything unused17
18# Docker daemon issues?19journalctl -xu docker.service # Check daemon logs (Linux)20sudo systemctl status docker # Check daemon status21sudo systemctl restart docker # Restart daemonDocker Compose
Basic Commands
bash
1docker compose up # Start all services (foreground)2docker compose up -d # Start in detached mode3docker compose up -d --build # Build images before starting4docker compose up -d --force-recreate # Recreate containers even if unchanged5docker compose up -d --no-deps web # Start specific service without dependencies6docker compose down # Stop and remove containers, networks7docker compose down -v # Also remove volumes8docker compose down --rmi all # Also remove images9docker compose stop # Stop services (don't remove)10docker compose start # Start stopped services11docker compose restart # Restart all services12docker compose restart web # Restart specific serviceBuild & Images
bash
1docker compose build # Build all services2docker compose build web # Build specific service3docker compose build --no-cache # Build without cache4docker compose pull # Pull all service images5docker compose push # Push all service imagesStatus & Logs
bash
1docker compose ps # List running services2docker compose ps -a # List all services (including stopped)3docker compose logs # View logs from all services4docker compose logs -f # Follow logs5docker compose logs web # Logs for specific service6docker compose logs --tail 50 web # Last 50 lines7docker compose logs --since 1h # Logs from last hour8docker compose top # Show running processesExecute & Run
bash
1docker compose exec web sh # Shell into running service2docker compose exec web bash # Bash into running service3docker compose exec -u root web sh # Shell as root4docker compose run web npm test # Run one-off command in new container5docker compose run --rm web npm test # Run and remove afterScaling & Config
bash
1docker compose up -d --scale web=3 # Scale service to 3 instances2docker compose config # Validate and show resolved config3docker compose config --services # List service names4docker compose config --volumes # List volume names5docker compose convert # Convert compose file to canonical formatCompose File Reference
bash
1docker compose -f compose.prod.yaml up -d # Use specific compose file2docker compose -f compose.yaml -f compose.override.yaml up -d # Merge multiple files3docker compose --env-file .env.prod up -d # Use specific env file4docker compose -p myproject up -d # Set project nameDocker Registry & Login
Authentication
bash
1docker login # Login to Docker Hub (interactive)2docker login -u myuser # Login with username3docker login registry.example.com # Login to private registry4docker logout # Logout from Docker Hub5docker logout registry.example.com # Logout from private registryWorking with Registries
bash
1# Docker Hub2docker pull nginx:latest3docker push myuser/myapp:v1.04
5# Private registry6docker pull registry.example.com/myapp:latest7docker push registry.example.com/myapp:latest8
9# Run a local registry10docker run -d -p 5000:5000 --name registry registry:211docker tag myapp localhost:5000/myapp:latest12docker push localhost:5000/myapp:latestDockerfile Quick Reference
Common Instructions
| Instruction | Description |
|---|---|
FROM | Base image |
WORKDIR | Set working directory |
COPY | Copy files from host to image |
ADD | Copy files (supports URLs and tar extraction) |
RUN | Execute command during build |
CMD | Default command when container starts |
ENTRYPOINT | Main executable (CMD becomes arguments) |
ENV | Set environment variable |
ARG | Build-time variable |
EXPOSE | Document which ports the container listens on |
VOLUME | Create mount point for volumes |
USER | Set user for subsequent instructions |
LABEL | Add metadata to image |
HEALTHCHECK | Define health check command |
.dockerignore | Exclude files from build context |
Example Multi-Stage Dockerfile
dockerfile
1# Build stage2FROM node:20-alpine AS builder3WORKDIR /app4COPY package*.json ./5RUN npm ci6COPY . .7RUN npm run build8
9# Production stage10FROM node:20-alpine11WORKDIR /app12COPY --from=builder /app/dist ./dist13COPY --from=builder /app/node_modules ./node_modules14EXPOSE 300015USER node16CMD ["node", "dist/index.js"]Cleanup & Maintenance
Prune Commands
bash
1docker container prune # Remove stopped containers2docker image prune # Remove dangling images3docker image prune -a # Remove all unused images4docker volume prune # Remove unused volumes5docker network prune # Remove unused networks6docker builder prune # Remove BuildKit cache7docker system prune # Remove all unused objects8docker system prune -a --volumes # Nuclear option — remove everything unusedDisk Usage
bash
1docker system df # Summary of disk usage2docker system df -v # Detailed disk usage per objectUseful Patterns
Health Checks
bash
1# In Dockerfile2HEALTHCHECK --interval=30s --timeout=5s --retries=3 \3 CMD curl -f http://localhost/ || exit 14
5# In docker run6docker run -d --health-cmd="curl -f http://localhost/ || exit 1" \7 --health-interval=30s --health-timeout=5s --health-retries=3 nginx8
9# Check health status10docker inspect -f '{{.State.Health.Status}}' my-containerResource Limits
bash
1docker run -d --memory=256m nginx # Memory limit2docker run -d --memory=256m --memory-swap=512m nginx # Memory + swap3docker run -d --cpus=1.5 nginx # CPU limit (1.5 cores)4docker run -d --cpu-shares=512 nginx # Relative CPU weight5docker run -d --pids-limit=100 nginx # Process count limitRestart Policies
| Policy | Description |
|---|---|
no | Never restart (default) |
on-failure[:max] | Restart on non-zero exit code |
always | Always restart |
unless-stopped | Always restart unless manually stopped |
bash
1docker run -d --restart=unless-stopped nginx2docker update --restart=always my-container # Update running containerOutput Formatting
Common Format Options
| Flag | Description |
|---|---|
--format "table ..." | Table with custom columns |
--format "{{json .}}" | JSON output |
--format "{{.ID}}" | Specific field |
-q / --quiet | IDs only |
--no-trunc | Don't truncate output |
Format Examples
bash
1# Custom container list2docker ps --format "table {{.ID}}\t{{.Names}}\t{{.Status}}\t{{.Ports}}"3
4# Get all container IPs5docker inspect -f '{{.Name}} - {{.NetworkSettings.IPAddress}}' $(docker ps -q)6
7# Image sizes sorted8docker images --format "{{.Repository}}:{{.Tag}} {{.Size}}" | sort -k2 -h9
10# JSON output for scripting11docker inspect --format '{{json .Config.Env}}' my-container | jq .