Cheatsheets

Docker

Docker

Docker is a containerization platform for building, shipping, and running applications in isolated environments. This cheatsheet covers essential Docker CLI commands.

6 Categories 16 Sections 48 Examples
Docker Containers Images DevOps Virtualization Deployment

Getting Started

Fundamental Docker concepts and basic setup for beginners.

What is Docker

Introduction to Docker and containerization concepts.

Docker overview

Docker is a lightweight virtualization platform that uses containerization to isolate applications and their dependencies.

Code
Terminal window
# Docker is a containerization platform that packages applications
# with their dependencies into isolated, portable containers.
# Key concepts:
# - Image: Blueprint/template for creating containers
# - Container: Running instance of an image
# - Registry: Repository for storing images (Docker Hub)
# - Daemon: Background service running Docker
Execution
Terminal window
docker --version
Output
Terminal window
Docker version 24.0.0, build abcd1234
  • Containers are more lightweight than virtual machines.
  • Docker uses images as templates to create containers.
  • All containers run on the same kernel but are isolated from each other.

Docker client-server architecture

Explains the client-server architecture of Docker and how commands flow through the system.

Code
Terminal window
# Docker uses a client-server architecture:
# 1. Client: CLI that sends commands to the daemon
# 2. Server: Daemon that manages containers and images
# 3. Registries: Stores images (public or private)
# Communication flow:
# Docker CLI → Docker Daemon → Container Runtime → Containers
Execution
Terminal window
docker info
Output
Terminal window
Client:
Version: 24.0.0
Server:
Containers: 3
Running: 1
Images: 15
  • The Docker daemon must be running for CLI commands to work.
  • Multiple clients can connect to one daemon.

Container vs image

Demonstrates the relationship between images and containers with concrete examples.

Code
Terminal window
# Image: Read-only template containing application code and dependencies
# - Similar to a class in object-oriented programming
# - Built from Dockerfile instructions
# - Immutable and portable
# Container: Running instance of an image
# - Similar to an object in object-oriented programming
# - Has writable layer on top of image
# - Each container is isolated with own filesystem, network, processes
Execution
Terminal window
docker images && docker ps
Output
Terminal window
REPOSITORY TAG IMAGE ID
ubuntu 20.04 1234567
CONTAINER ID IMAGE STATUS
abcd1234 ubuntu Up 2 hours
  • One image can create multiple containers.
  • Containers are ephemeral and data is lost when stopped (unless using volumes).

Installation Setup

Installing Docker and verifying the installation.

Install Docker on Linux

Installation steps for Docker on Ubuntu/Debian-based Linux systems.

Code
Terminal window
# Update package manager
sudo apt-get update
# Install Docker package
sudo apt-get install -y docker.io
# Start Docker daemon
sudo systemctl start docker
# Enable Docker to start on boot
sudo systemctl enable docker
Execution
Terminal window
sudo docker --version
Output
Terminal window
Docker version 24.0.0, build abcd1234
  • Requires Ubuntu 16.04 LTS or newer.
  • Using `sudo` is necessary for Docker commands unless configured otherwise.

Post-installation setup

Post-installation configuration to run Docker without sudo and verify the setup.

Code
Terminal window
# Run Docker without sudo (optional)
sudo usermod -aG docker $USER
# Apply group membership
newgrp docker
# Verify installation
docker run hello-world
Execution
Terminal window
docker run hello-world
Output
Terminal window
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
Status: Downloaded newer image for hello-world:latest
Hello from Docker!
  • Adding user to docker group allows running without sudo.
  • Must logout and login again for group changes to take effect.

Docker Desktop installation (macOS/Windows)

Installation instructions for Docker Desktop on macOS and Windows systems.

Code
Terminal window
# macOS: Install using Homebrew
brew install --cask docker
# Or download from: https://www.docker.com/products/docker-desktop
# Windows: Download Docker Desktop installer from official site
# Then run installer and enable WSL 2 integration
# After installation, verify
docker --version
Execution
Terminal window
docker --version && docker run hello-world
Output
Terminal window
Docker version 24.0.0, build abcd1234
Hello from Docker!
  • Docker Desktop includes Docker engine, CLI, and Docker Compose.
  • Windows requires WSL 2 (Windows Subsystem for Linux 2) for optimal performance.

Hello World

Running your first Docker container.

Run hello-world image

Demonstrates the basic workflow of pulling an image and running a container.

Code
Terminal window
docker run hello-world
Execution
Terminal window
docker run hello-world
Output
Terminal window
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
2db29710123e: Pull complete
Status: Downloaded newer image for hello-world:latest
Hello from Docker!
This message shows that your installation appears to be working correctly.
  • Docker downloads the image from Docker Hub if it's not already present.
  • The container runs and exits automatically for hello-world.

Run interactive shell container

Runs an interactive shell in an Ubuntu container, allowing you to explore the container filesystem.

Code
Terminal window
docker run -it ubuntu:22.04 /bin/bash
Execution
Terminal window
docker run -it ubuntu:22.04 /bin/bash
Input
Terminal window
ls -la
exit
Output
Terminal window
total 32
drwxr-xr-x 1 root root 4096 Jan 10 12:00 .
drwxr-xr-x 1 root root 4096 Jan 10 12:00 ..
-rwxr-xr-x 1 root root 0 Jan 10 12:00 .dockerenv
...
  • `-it` flags enable interactive terminal access.
  • Type `exit` to leave the container.

Run container with custom command

Runs a specific command in the container and then exits.

Code
Terminal window
docker run --name my-python-app python:3.11 python --version
Execution
Terminal window
docker run --name my-python-app python:3.11 python --version
Output
Terminal window
Python 3.11.5
  • `--name` assigns a friendly name to the container.
  • Container exits after command completes.

Build & Images

Creating, managing, and working with Docker images.

Docker Build

Creating Docker images from Dockerfiles.

Basic Docker build

Demonstrates basic Docker image building with tag naming.

Code
Terminal window
# Create a Dockerfile
cat > Dockerfile << 'EOF'
FROM ubuntu:22.04
RUN apt-get update && apt-get install -y curl
COPY . /app
WORKDIR /app
CMD ["echo", "Hello from Docker!"]
EOF
# Build the image
docker build -t my-app:1.0 .
Execution
Terminal window
docker build -t my-app:1.0 .
Output
Terminal window
Sending build context to Docker daemon 2.048kB
Step 1/5 : FROM ubuntu:22.04
Step 2/5 : RUN apt-get update && apt-get install -y curl
Step 3/5 : COPY . /app
Step 4/5 : WORKDIR /app
Step 5/5 : CMD ["echo", "Hello from Docker!"]
Successfully built abc123def456
Successfully tagged my-app:1.0
  • Build context includes all files in current directory.
  • Tag format is `repository:tag` or `registry/repository:tag`.
  • Each RUN instruction creates a layer.

Build with build arguments

Demonstrates build-time arguments for customizing image builds.

Code
Terminal window
# Dockerfile with build arguments
cat > Dockerfile << 'EOF'
FROM python:3.11
ARG APP_VERSION=1.0
ARG APP_ENV=production
RUN echo "Building version $APP_VERSION for $APP_ENV"
COPY . /app
WORKDIR /app
RUN pip install -r requirements.txt
CMD ["python", "app.py"]
EOF
# Build with custom arguments
docker build \
--build-arg APP_VERSION=2.5 \
--build-arg APP_ENV=staging \
-t my-python-app:2.5 .
Execution
Terminal window
docker build --build-arg APP_VERSION=2.5 -t my-python-app:2.5 .
Output
Terminal window
Sending build context to Docker daemon
Step 1/7 : FROM python:3.11
Step 2/7 : ARG APP_VERSION=1.0
Step 3/7 : ARG APP_ENV=production
Step 4/7 : RUN echo "Building version 2.5 for staging"
Building version 2.5 for staging
Successfully tagged my-python-app:2.5
  • ARG values can be overridden during build time.
  • Build arguments are only available during build, not in running containers.

Multi-stage Docker build

Multi-stage builds reduce final image size by using temporary build stages.

Code
Terminal window
cat > Dockerfile << 'EOF'
# Build stage
FROM golang:1.21 as builder
WORKDIR /app
COPY . .
RUN go build -o myapp
# Runtime stage
FROM alpine:latest
WORKDIR /root/
COPY --from=builder /app/myapp .
CMD ["./myapp"]
EOF
docker build -t go-optimized:latest .
Execution
Terminal window
docker build -t go-optimized:latest .
Output
Terminal window
Step 1/8 : FROM golang:1.21 as builder
Step 2/8 : WORKDIR /app
Step 3/8 : COPY . .
Step 4/8 : RUN go build -o myapp
Step 5/8 : FROM alpine:latest
Step 6/8 : WORKDIR /root/
Step 7/8 : COPY --from=builder /app/myapp .
Step 8/8 : CMD ["./myapp"]
Successfully tagged go-optimized:latest
  • Only final stage is included in the image.
  • Significantly reduces image size for compiled applications.

Managing Images

Listing, inspecting, and managing Docker images.

List all images

Displays all Docker images and their metadata.

Code
Terminal window
# List all local images
docker images
# List with all details including dangling images
docker images -a
Execution
Terminal window
docker images
Output
Terminal window
REPOSITORY TAG IMAGE ID CREATED SIZE
ubuntu 22.04 6b038c8a0437 2 weeks ago 77.9MB
python 3.11 abc123def456 2 weeks ago 920MB
nginx latest def456abc123 1 week ago 187MB
my-app 1.0 xyz789abc123 3 days ago 250MB
  • IMAGE ID is the unique identifier for the image.
  • SIZE is the uncompressed size of the image.

Inspect image details

Shows detailed JSON metadata about a specific image.

Code
Terminal window
# Get detailed information about an image
docker inspect ubuntu:22.04
# Get specific information using jq
docker inspect ubuntu:22.04 | jq '.[0].Config.Env'
Execution
Terminal window
docker inspect ubuntu:22.04
Output
Terminal window
[
{
"Id": "sha256:6b038c8a043...",
"RepoTags": ["ubuntu:22.04"],
"Size": 77880000,
"Architecture": "amd64",
"Config": {
"Hostname": "",
"Env": ["PATH=/usr/local/sbin:/usr/local/bin:..."]
}
}
]
  • Output is in JSON format.
  • Includes environment variables, exposed ports, and more.

View image history

Displays the build history showing each layer and command.

Code
Terminal window
# Show image build history (layers)
docker history my-app:1.0
# Show human-readable format
docker history --human my-app:1.0
Execution
Terminal window
docker history my-app:1.0
Output
Terminal window
IMAGE CREATED CREATED BY SIZE
abc123def456 3 hours ago /bin/sh -c #(nop) CMD ["pytho 0B
def456abc123 3 hours ago /bin/sh -c pip install -r req 45MB
ghi789def012 3 hours ago /bin/sh -c #(nop) COPY dir:... 2.5MB
python:3.11 2 weeks ago /bin/sh -c #(nop) CMD ["pyth 0B
  • Each row represents a layer in the image.
  • Helps understand what commands created each layer.

Remove Images

Deleting Docker images and managing disk space.

Remove single image by ID

Removes a Docker image by its ID.

Code
Terminal window
# Remove image by ID
docker rmi abc123def456
# Force remove even if in use
docker rmi -f abc123def456
Execution
Terminal window
docker rmi abc123def456
Output
Terminal window
Untagged: my-app:1.0
Deleted: sha256:abc123def456...
Deleted: sha256:def456abc123...
  • Cannot remove image if running containers use it.
  • Use `-f` flag to force remove, but may orphan containers.

Remove image by repository name

Removes Docker images by repository and tag name.

Code
Terminal window
# Remove specific image tag
docker rmi ubuntu:22.04
# Remove all tags of repository
docker rmi ubuntu
Execution
Terminal window
docker rmi python:3.11
Output
Terminal window
Untagged: python:3.11
Deleted: sha256:abc123def456...
Deleted: sha256:def456abc123...
  • Remove containers first before removing images they use.

Remove dangling images

Cleans up unused and dangling images to free disk space.

Code
Terminal window
# Find dangling images (untagged, unused layers)
docker images -f dangling=true
# Remove all dangling images
docker image prune -a
# Remove with confirmation
docker image prune -a --force
Execution
Terminal window
docker image prune -a
Output
Terminal window
WARNING! This will remove all images without at least one container associated to them.
Are you sure you want to continue? [y/N] y
Deleted Images:
untagged: old-app:1.0@sha256:...
total reclaimed space: 245.3MB
  • Dangling images have no repository or tag reference.
  • This operation is irreversible.

Run & Containers

Creating and running Docker containers with various options.

Docker Run

Creating and starting containers with the run command.

Basic container run

Demonstrates basic run options for different scenarios.

Code
Terminal window
# Run container and keep it running
docker run -d --name my-web nginx:latest
# Run with interactive terminal
docker run -it ubuntu:22.04 /bin/bash
# Run and remove after exit
docker run --rm python:3.11 python --version
Execution
Terminal window
docker run -d --name my-web nginx:latest
Output
Terminal window
1a2b3c4d5e6f7g8h9i0j (container ID)
  • `-d` runs container in detached (background) mode.
  • `-it` allows interactive terminal access.
  • `--rm` automatically removes container when it exits.

Run with port mapping and volumes

Maps container ports to host and mounts volumes.

Code
Terminal window
# Map container port to host port
docker run -d -p 8080:80 --name my-web \
-v /var/www/html:/usr/share/nginx/html \
nginx:latest
# Multiple port mappings
docker run -d -p 80:80 -p 443:443 \
--name my-secure-web nginx:latest
Execution
Terminal window
docker run -d -p 8080:80 --name my-web nginx:latest
Output
Terminal window
abc123def456ghi789jkl
  • Format is `-p host_port:container_port`.
  • `-v` mounts host directory into container.
  • Must use absolute paths for volume mounting.

Run with environment variables and resource limits

Demonstrates environment variables and resource constraints.

Code
Terminal window
# Set environment variables
docker run -d --name my-app \
-e DATABASE_URL=postgres://db:5432 \
-e APP_ENV=production \
-e LOG_LEVEL=info \
my-app:1.0
# Set resource limits
docker run -d --name my-limited-app \
-m 512m \
--cpus="0.5" \
my-app:1.0
Execution
Terminal window
docker run -d -e APP_ENV=production my-app:1.0
Output
Terminal window
xyz123abc456def789ghi
  • `-e` sets environment variables in the container.
  • `-m` limits memory in MB or GB.
  • `--cpus` limits CPU resources.

Docker Create

Creating containers without starting them immediately.

Create container configuration

Separates container creation from startup for more control.

Code
Terminal window
# Create container without starting
docker create --name my-db \
-e MYSQL_ROOT_PASSWORD=secret \
-p 3306:3306 \
-v db-data:/var/lib/mysql \
mysql:8.0
# Verify it's created but not running
docker ps -a
Execution
Terminal window
docker create --name my-db mysql:8.0
Output
Terminal window
abc123def456ghi789jkl (container ID)
  • Container is created but in stopped state.
  • Useful for configuring containers before starting.

Create with advanced networking

Creates containers on specific networks for container-to-container communication.

Code
Terminal window
# Create network
docker network create my-network
# Create container on specific network
docker create --name web-server \
--network my-network \
--network-alias web \
-p 80:80 \
nginx:latest
# Create another container on same network
docker create --name app-server \
--network my-network \
my-app:1.0
Execution
Terminal window
docker create --network my-network --name web-server nginx:latest
Output
Terminal window
def456ghi789jkl123abc
  • Containers on same network can communicate using container name.
  • Network aliases provide DNS resolution within the network.

Create with health check

Creates container with health check for monitoring availability.

Code
Terminal window
# Create with health check
docker create --name healthy-app \
--health-cmd="curl -f http://localhost:8080/health || exit 1" \
--health-interval=30s \
--health-timeout=10s \
--health-retries=3 \
my-app:1.0
Execution
Terminal window
docker create --health-cmd="curl localhost:8080" my-app:1.0
Output
Terminal window
ghi789jkl123abc456def
  • Health check runs at specified intervals.
  • Docker marks container as unhealthy after retries fail.

Docker Exec

Running commands inside running containers.

Execute command in running container

Executes a command inside a running container without entering shell.

Code
Terminal window
# Execute single command
docker exec my-web ls -la /var/www/html
# Execute with output
docker exec my-db mysql -u root -p$MYSQL_ROOT_PASSWORD -e "SHOW DATABASES;"
Execution
Terminal window
docker exec my-web ls -la /var/www/html
Output
Terminal window
total 24
drwxr-xr-x 1 root root 4096 Jan 10 12:00 .
drwxr-xr-x 1 root root 4096 Jan 10 12:00 ..
-rw-r--r-- 1 root root 1234 Jan 10 12:00 index.html
  • Container must be in running state.
  • Useful for quick debugging and inspection.

Interactive shell access

Provides interactive shell access for debugging and exploration.

Code
Terminal window
# Enter interactive shell
docker exec -it my-app /bin/bash
# Once inside, run commands
# $ ps aux
# $ cat /var/log/app.log
# $ exit
Execution
Terminal window
docker exec -it my-app /bin/bash
Input
Terminal window
id
pwd
Output
Terminal window
uid=0(root) gid=0(root) groups=0(root)
/app
  • `-it` enables interactive terminal mode.
  • Type `exit` to leave the shell.

Execute with user and working directory

Demonstrates user, directory, and background execution options.

Code
Terminal window
# Execute as specific user
docker exec -u appuser my-app whoami
# Execute in specific directory
docker exec -w /var/log my-app tail -f app.log
# Execute in background
docker exec -d my-app python script.py
Execution
Terminal window
docker exec -u appuser my-app whoami
Output
Terminal window
appuser
  • `-u` specifies user for command execution.
  • `-w` sets working directory for command.
  • `-d` runs command in background.

Container Management

Managing container lifecycle, status, and logs.

Start & Stop Containers

Starting, stopping, and restarting containers.

Start and stop containers

Basic container lifecycle operations.

Code
Terminal window
# Stop a running container gracefully
docker stop my-web
# Start a stopped container
docker start my-web
# Restart a container (stop then start)
docker restart my-web
Execution
Terminal window
docker stop my-web && docker start my-web
Output
Terminal window
my-web
my-web
  • `stop` sends SIGTERM signal, gives 10 seconds to shutdown gracefully.
  • `start` restarts stopped container with same configuration.

Stop with timeout and force kill

Advanced stop options including timeout and force kill.

Code
Terminal window
# Stop with custom timeout before killing
docker stop -t 30 my-web
# Force kill container immediately
docker kill my-web
# Kill all running containers
docker kill $(docker ps -q)
Execution
Terminal window
docker stop -t 30 my-web
Output
Terminal window
my-web
  • `-t` specifies seconds to wait before killing (default 10).
  • `kill` sends SIGKILL immediately, no graceful shutdown.

Pause and unpause containers

Temporarily pause container processes without stopping container.

Code
Terminal window
# Pause all processes in container
docker pause my-app
# Resume paused container
docker unpause my-app
# Check pause status
docker inspect -f '{{.State.Paused}}' my-app
Execution
Terminal window
docker pause my-app && docker unpause my-app
Output
Terminal window
my-app
my-app
  • Paused containers still consume memory.
  • Useful for resource management without full stop.

List Containers

Listing and filtering containers.

List running containers

Lists Docker containers with various output options.

Code
Terminal window
# List running containers
docker ps
# List all containers (running and stopped)
docker ps -a
# List only container IDs
docker ps -q
Execution
Terminal window
docker ps
Output
Terminal window
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
abc123def456 nginx:latest "nginx..." 2 hours ago Up 2 hours 0.0.0.0:8080->80/tcp
def456ghi789 mysql:8.0 "docker..." 1 hour ago Up 1 hour 3306/tcp
  • Default `ps` shows only running containers.
  • `-a` includes stopped containers.
  • `-q` shows only IDs for scripting.

Filter containers by status and labels

Advanced filtering options for container queries.

Code
Terminal window
# Filter by status
docker ps -a -f status=exited
docker ps -a -f status=running
# Filter by label
docker ps -f label=environment=production
# Filter by image
docker ps -f ancestor=nginx:latest
Execution
Terminal window
docker ps -a -f status=exited
Output
Terminal window
CONTAINER ID IMAGE STATUS
xyz123abc456 ubuntu:20.04 Exited (0)
ghi789jkl012 python:3.11 Exited (1)
  • Multiple filters can be combined with `-f`.
  • Labels must be set when creating containers.

Custom output formatting

Custom formatting options for better readability.

Code
Terminal window
# Show custom columns
docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
# JSON format
docker ps --format json
# Simple list of names
docker ps --no-trunc --format "{{.Names}}"
Execution
Terminal window
docker ps --format "table {{.Names}}\t{{.Status}}"
Output
Terminal window
NAMES STATUS
my-web Up 2 hours
my-db Up 1 hour
  • `--format` accepts template variables.
  • Useful for scripting and automation.

Docker Logs

Viewing and monitoring container logs.

View container logs

Displays container output and logs.

Code
Terminal window
# View all logs
docker logs my-web
# View last 50 lines
docker logs --tail 50 my-web
# View logs with timestamps
docker logs -t my-web
Execution
Terminal window
docker logs my-web
Output
Terminal window
/docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to start nginx
/docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/
2025-01-10T12:00:00.123Z [notice] starting server...
2025-01-10T12:00:00.456Z [notice] listen() to 0.0.0.0:80
  • Logs are from container's stdout and stderr.
  • Can view logs even after container stops.

Follow logs in real-time

Real-time log streaming for monitoring container activity.

Code
Terminal window
# Stream logs in real-time (like tail -f)
docker logs -f my-web
# Stream with timestamps
docker logs -f -t my-web
# Stream last 10 lines with follow
docker logs --tail 10 -f my-web
# Press Ctrl+C to exit
Execution
Terminal window
docker logs -f my-web
Output
Terminal window
2025-01-10T12:00:05.123Z GET / HTTP/1.1 200
2025-01-10T12:00:06.456Z GET /api/users HTTP/1.1 200
2025-01-10T12:00:07.789Z GET /style.css HTTP/1.1 304
(continue streaming...)
  • `-f` follows log output continuously.
  • Press Ctrl+C to stop streaming.

Filter and search logs

Filters and searches logs for specific patterns.

Code
Terminal window
# Show logs since specific time
docker logs --since 2025-01-10T12:00:00 my-web
# Show logs from last hour
docker logs --since 1h my-web
# Search for specific patterns
docker logs my-web | grep ERROR
docker logs my-web | grep -i exception
Execution
Terminal window
docker logs my-web | grep ERROR
Output
Terminal window
2025-01-10T12:00:15.123Z [ERROR] Connection timeout
2025-01-10T12:00:30.456Z [ERROR] Database unavailable
  • `--since` accepts timestamps or duration.
  • Combine with grep for sophisticated searches.

Networking & Volumes

Container networking, port mapping, and persistent storage.

Port Mapping & Networking

Managing ports, networks, and container communication.

Port mapping

Maps container ports to host for external access.

Code
Terminal window
# Map single port
docker run -d -p 8080:80 --name my-web nginx:latest
# Map multiple ports
docker run -d -p 80:80 -p 443:443 -p 3000:3000 my-app:1.0
# Map to specific host interface
docker run -d -p 127.0.0.1:8080:80 my-web
# Dynamic port mapping (OS assigns port)
docker run -d -P nginx:latest
Execution
Terminal window
docker run -d -p 8080:80 nginx:latest
Output
Terminal window
abc123def456ghi789jkl
  • Format: `-p host_port:container_port`.
  • `-P` auto-assigns high ports above 32768.
  • Access locally: `http://localhost:8080`.

Docker networks and container linking

Creates custom networks for container-to-container communication.

Code
Terminal window
# Create custom bridge network
docker network create my-app-network
# Run containers on network
docker run -d --name web \
--network my-app-network \
-p 8080:80 \
nginx:latest
docker run -d --name db \
--network my-app-network \
-e MYSQL_ROOT_PASSWORD=secret \
mysql:8.0
# Containers can communicate using names
docker exec web curl http://db:3306
Execution
Terminal window
docker network create my-app-network
Output
Terminal window
abc123def456ghi789jklmnopq
  • Containers on same network can communicate using names.
  • Better than deprecated `--link` option.

Inspect and manage networks

Manages and inspects Docker networks.

Code
Terminal window
# List networks
docker network ls
# Inspect network details
docker network inspect my-app-network
# Connect container to network
docker network connect my-app-network container-name
# Disconnect from network
docker network disconnect my-app-network container-name
Execution
Terminal window
docker network ls
Output
Terminal window
NETWORK ID NAME DRIVER SCOPE
abc123def456 bridge bridge local
def456ghi789 host host local
ghi789jkl012 none null local
jkl012mno345 my-app-network bridge local
  • bridge: Default, isolated network.
  • host: Uses host network.
  • none: No networking.

Docker Volumes

Volume management for persistent data storage.

Create and manage volumes

Creates and manages named volumes for persistent storage.

Code
Terminal window
# Create named volume
docker volume create db-data
# List volumes
docker volume ls
# Inspect volume
docker volume inspect db-data
# Remove volume
docker volume rm db-data
Execution
Terminal window
docker volume create db-data
Output
Terminal window
db-data
  • Named volumes are stored on host at `/var/lib/docker/volumes/`.
  • Volumes persist even when containers are removed.

Mount volumes in containers

Mounts volumes and bind mounts in containers.

Code
Terminal window
# Mount named volume
docker run -d -v db-data:/var/lib/mysql \
--name my-db mysql:8.0
# Bind mount from host directory
docker run -d -v /data/app:/app \
--name my-app my-app:1.0
# Read-only mount
docker run -d -v db-data:/data:ro \
--name web-app my-web:1.0
Execution
Terminal window
docker run -d -v db-data:/var/lib/mysql mysql:8.0
Output
Terminal window
xyz123abc456def789ghi
  • Format: `-v volume_name:/container_path`.
  • Use absolute paths for bind mounts.
  • Add `:ro` for read-only mount.

Share data between containers

Uses volumes to share data between multiple containers.

Code
Terminal window
# Create shared volume
docker volume create shared-data
# Container 1 writes to volume
docker run -d -v shared-data:/data \
--name writer my-writer:1.0
# Container 2 reads from same volume
docker run -d -v shared-data:/shared \
--name reader my-reader:1.0
# Verify data is shared
docker exec writer sh -c "echo 'shared data' > /data/file.txt"
docker exec reader cat /shared/file.txt
Execution
Terminal window
docker volume create shared-data
Output
Terminal window
shared-data
  • Multiple containers can mount same volume.
  • Useful for shared configuration and data.

Cleanup & System

Removing containers, cleaning unused resources, and system management.

Container & Image Cleanup

Removing containers and managing disk space.

Remove containers

Removes Docker containers to free resources.

Code
Terminal window
# Remove stopped container
docker rm container-name
# Remove running container (force)
docker rm -f container-name
# Remove multiple containers
docker rm container1 container2 container3
# Remove all stopped containers
docker container prune
Execution
Terminal window
docker rm stopped-container
Output
Terminal window
stopped-container
  • Use `-f` to force remove running containers.
  • Cannot remove without -f if container is running.

Prune system resources

Comprehensive cleanup of unused Docker resources.

Code
Terminal window
# Remove dangling images, containers, volumes, networks
docker system prune
# Also remove unused images (not just dangling)
docker system prune -a
# Include volumes in cleanup
docker system prune -a --volumes
Execution
Terminal window
docker system prune -a
Output
Terminal window
WARNING! This will remove:
- all stopped containers
- all networks not used by at least one container
- all dangling images
- all build cache
Total reclaimed space: 2.5GB
  • `prune` is irreversible; review what will be removed.
  • Use `-a` to remove all unused images.

Cleanup specific resources

Targeted cleanup of specific resource types.

Code
Terminal window
# Remove dangling images only
docker image prune
# Remove unused volumes
docker volume prune
# Stop all containers and remove them
docker stop $(docker ps -q)
docker rm $(docker ps -a -q)
# Remove images matching pattern
docker rmi $(docker images | grep 'old-app' | awk '{print $3}')
Execution
Terminal window
docker image prune
Output
Terminal window
WARNING! This will remove all dangling images.
Total reclaimed space: 512MB
  • Can be more selective than system prune.
  • Useful for specific cleanup scenarios.

System Management

Monitoring Docker system health and resource usage.

Monitor Docker disk usage

Shows Docker's resource consumption and disk usage.

Code
Terminal window
# Show Docker disk usage
docker system df
# Show detailed info
docker system df -v
# Show system information
docker system info
Execution
Terminal window
docker system df
Output
Terminal window
TYPE TOTAL ACTIVE SIZE RECLAIMABLE
Images 15 3 2.5GB 1.8GB
Containers 8 2 256MB 200MB
Local Volumes 12 4 512MB 100MB
  • TOTAL: Total count of resources.
  • ACTIVE: Currently in use.
  • RECLAIMABLE: Space that could be freed.

Monitor container statistics

Shows real-time resource usage for running containers.

Code
Terminal window
# Show container resource usage
docker stats
# Show stats for specific containers
docker stats my-web my-db
# Show without streaming (one snapshot)
docker stats --no-stream
Execution
Terminal window
docker stats --no-stream
Output
Terminal window
CONTAINER CPU % MEM USAGE MEM % NET I/O
my-web 0.25% 45MB 5% 12MB/8MB
my-db 2.15% 185MB 18% 150MB/120MB
  • CPU %, Memory, Network I/O statistics.
  • Useful for identifying resource hogs.

Get system events

Monitors Docker system events in real-time.

Code
Terminal window
# Show system events in real-time
docker system events
# Filter events for containers
docker system events --filter type=container
# Filter for specific container
docker system events --filter container=my-web
Execution
Terminal window
docker system events --filter type=container
Output
Terminal window
2025-01-10T12:00:15.123Z container create abc123def456
2025-01-10T12:00:16.456Z container start abc123def456
2025-01-10T12:00:45.789Z container stop abc123def456
  • Events include create, start, stop, delete, etc.
  • Filter by type (container, image, volume, etc.).