Docker Cheat Sheet

A comprehensive reference of Docker commands with examples and usage instructions. Find the command you need using the search bar or browse by category.

56 commands found
Filter by category:

docker version

Setup & Installation

Display Docker version information

Syntax:

docker version [OPTIONS]

Examples:

docker version Show Docker version info
docker version --format '{{.Server.Version}}' Show only server version
docker --version Short version display

Notes:

Useful for checking Docker installation and client/server versions

docker info

Setup & Installation

Display system-wide information

Syntax:

docker info [OPTIONS]

Examples:

docker info Show detailed system information
docker info --format '{{.ContainersRunning}}' Show only running containers count
docker info | grep 'Storage Driver' Check storage driver

Notes:

Shows containers, images, storage driver, and kernel version

docker login

Setup & Installation

Log in to a Docker registry

Syntax:

docker login [SERVER]

Examples:

docker login Log in to Docker Hub
docker login registry.example.com Log in to private registry
docker login -u username Log in with specific username

Notes:

Credentials are stored in ~/.docker/config.json

docker logout

Setup & Installation

Log out from a Docker registry

Syntax:

docker logout [SERVER]

Examples:

docker logout Log out from Docker Hub
docker logout registry.example.com Log out from private registry

Notes:

Removes stored credentials from config file

docker run

Container Management

Create and start a new container

Syntax:

docker run [OPTIONS] IMAGE [COMMAND] [ARG...]

Examples:

docker run hello-world Run hello-world container
docker run -it ubuntu bash Run Ubuntu interactively
docker run -d -p 8080:80 nginx Run nginx in background on port 8080
docker run --name mycontainer nginx Run with custom name
docker run -v /host/path:/container/path nginx Run with volume mount
docker run --rm alpine echo 'Hello World' Run and auto-remove after exit

Notes:

Most commonly used Docker command for creating containers

docker ps

Container Management

List running containers

Syntax:

docker ps [OPTIONS]

Examples:

docker ps List running containers
docker ps -a List all containers (including stopped)
docker ps -q List only container IDs
docker ps --filter 'status=exited' List only exited containers
docker ps --format 'table {{.Names}}\t{{.Status}}' Custom output format

Notes:

Use -a to see all containers, not just running ones

docker start

Container Management

Start stopped containers

Syntax:

docker start [OPTIONS] CONTAINER [CONTAINER...]

Examples:

docker start mycontainer Start container by name
docker start 1a2b3c4d Start container by ID
docker start -a mycontainer Start and attach to container
docker start $(docker ps -aq) Start all stopped containers

Notes:

Containers retain their configuration from when they were created

docker stop

Container Management

Stop running containers

Syntax:

docker stop [OPTIONS] CONTAINER [CONTAINER...]

Examples:

docker stop mycontainer Stop container by name
docker stop 1a2b3c4d Stop container by ID
docker stop -t 30 mycontainer Stop with 30 second timeout
docker stop $(docker ps -q) Stop all running containers

Notes:

Sends SIGTERM, then SIGKILL after timeout (default 10s)

docker restart

Container Management

Restart containers

Syntax:

docker restart [OPTIONS] CONTAINER [CONTAINER...]

Examples:

docker restart mycontainer Restart container by name
docker restart -t 30 mycontainer Restart with custom timeout
docker restart $(docker ps -aq) Restart all containers

Notes:

Equivalent to running docker stop followed by docker start

docker rm

Container Management

Remove containers

Syntax:

docker rm [OPTIONS] CONTAINER [CONTAINER...]

Examples:

docker rm mycontainer Remove container by name
docker rm -f mycontainer Force remove running container
docker rm $(docker ps -aq) Remove all containers
docker rm $(docker ps -f status=exited -q) Remove all exited containers

Notes:

Container must be stopped first unless using -f flag

docker exec

Container Management

Execute commands in running containers

Syntax:

docker exec [OPTIONS] CONTAINER COMMAND [ARG...]

Examples:

docker exec -it mycontainer bash Open interactive bash shell
docker exec mycontainer ls -la List files in container
docker exec -u root mycontainer apt update Run command as root user
docker exec -w /app mycontainer pwd Run command in specific directory

Notes:

Container must be running to use exec

docker logs

Container Management

Fetch container logs

Syntax:

docker logs [OPTIONS] CONTAINER

Examples:

docker logs mycontainer Show all logs
docker logs -f mycontainer Follow log output in real-time
docker logs --tail 50 mycontainer Show last 50 lines
docker logs --since 2h mycontainer Show logs from last 2 hours
docker logs -t mycontainer Show timestamps

Notes:

Only shows logs from STDOUT and STDERR

docker inspect

Container Management

Display detailed container information

Syntax:

docker inspect [OPTIONS] NAME|ID [NAME|ID...]

Examples:

docker inspect mycontainer Show full container details
docker inspect --format '{{.NetworkSettings.IPAddress}}' mycontainer Show container IP address
docker inspect --format '{{.State.Status}}' mycontainer Show container status
docker inspect --format '{{.Config.Image}}' mycontainer Show container image

Notes:

Returns JSON data with comprehensive container information

docker stats

Container Management

Display live resource usage statistics

Syntax:

docker stats [OPTIONS] [CONTAINER...]

Examples:

docker stats Show stats for all running containers
docker stats mycontainer Show stats for specific container
docker stats --no-stream Show stats once and exit
docker stats --format 'table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}' Custom stats format

Notes:

Shows CPU, memory, network, and block I/O usage in real-time

docker build

Image Operations

Build Docker images from Dockerfile

Syntax:

docker build [OPTIONS] PATH | URL | -

Examples:

docker build . Build image from current directory
docker build -t myapp:latest . Build and tag image
docker build -f Dockerfile.prod . Use specific Dockerfile
docker build --no-cache . Build without using cache
docker build --build-arg VERSION=1.0 . Pass build arguments

Notes:

Dockerfile must be in the build context (usually current directory)

docker images

Image Operations

List Docker images

Syntax:

docker images [OPTIONS] [REPOSITORY[:TAG]]

Examples:

docker images List all images
docker images -a Show all images including intermediates
docker images -q Show only image IDs
docker images --filter 'dangling=true' Show dangling images
docker images --format 'table {{.Repository}}\t{{.Tag}}\t{{.Size}}' Custom format

Notes:

Use 'docker image ls' as modern alternative

docker pull

Image Operations

Download images from registry

Syntax:

docker pull [OPTIONS] NAME[:TAG|@DIGEST]

Examples:

docker pull ubuntu Pull latest Ubuntu image
docker pull ubuntu:20.04 Pull specific Ubuntu version
docker pull --all-tags ubuntu Pull all tags for Ubuntu
docker pull registry.example.com/myapp Pull from private registry

Notes:

Defaults to 'latest' tag if no tag specified

docker push

Image Operations

Upload images to registry

Syntax:

docker push [OPTIONS] NAME[:TAG]

Examples:

docker push myusername/myapp Push to Docker Hub
docker push myusername/myapp:v1.0 Push specific tag
docker push registry.example.com/myapp Push to private registry

Notes:

Image must be tagged appropriately before pushing

docker rmi

Image Operations

Remove Docker images

Syntax:

docker rmi [OPTIONS] IMAGE [IMAGE...]

Examples:

docker rmi myimage Remove image by name
docker rmi -f myimage Force remove image
docker rmi $(docker images -q) Remove all images
docker rmi $(docker images -f dangling=true -q) Remove dangling images

Notes:

Cannot remove images being used by containers unless forced

docker tag

Image Operations

Tag images with new names

Syntax:

docker tag SOURCE_IMAGE[:TAG] TARGET_IMAGE[:TAG]

Examples:

docker tag myapp myapp:v1.0 Add version tag
docker tag myapp:latest myusername/myapp:latest Tag for Docker Hub
docker tag local-image registry.example.com/myapp Tag for private registry

Notes:

Creates a new reference to existing image data

docker save

Image Operations

Save images to tar archive

Syntax:

docker save [OPTIONS] IMAGE [IMAGE...]

Examples:

docker save myapp > myapp.tar Save image to tar file
docker save -o myapp.tar myapp Save using output flag
docker save myapp:v1 myapp:v2 > myapp-versions.tar Save multiple tags

Notes:

Useful for offline image distribution

docker load

Image Operations

Load images from tar archive

Syntax:

docker load [OPTIONS]

Examples:

docker load < myapp.tar Load image from tar file
docker load -i myapp.tar Load using input flag
docker load --quiet < myapp.tar Load without verbose output

Notes:

Restores images saved with docker save

docker history

Image Operations

Show image layer history

Syntax:

docker history [OPTIONS] IMAGE

Examples:

docker history myapp Show image build history
docker history --no-trunc myapp Show full command history
docker history -q myapp Show only layer IDs

Notes:

Displays the commands used to create each layer

docker-compose up

Docker Compose

Create and start containers defined in docker-compose.yml

Syntax:

docker-compose up [OPTIONS] [SERVICE...]

Examples:

docker-compose up Start all services
docker-compose up -d Start services in background
docker-compose up --build Rebuild images before starting
docker-compose up web Start only web service
docker-compose up --scale web=3 Start 3 instances of web service

Notes:

Looks for docker-compose.yml in current directory

docker-compose down

Docker Compose

Stop and remove containers, networks

Syntax:

docker-compose down [OPTIONS]

Examples:

docker-compose down Stop and remove containers
docker-compose down -v Also remove volumes
docker-compose down --rmi all Also remove all images
docker-compose down --remove-orphans Remove orphaned containers

Notes:

Stops containers and removes containers, networks, volumes, and images

docker-compose ps

Docker Compose

List containers for the project

Syntax:

docker-compose ps [OPTIONS] [SERVICE...]

Examples:

docker-compose ps List all project containers
docker-compose ps -q List only container IDs
docker-compose ps web List containers for web service only

Notes:

Shows containers created by current docker-compose.yml

docker-compose logs

Docker Compose

View output from containers

Syntax:

docker-compose logs [OPTIONS] [SERVICE...]

Examples:

docker-compose logs Show logs for all services
docker-compose logs -f Follow logs in real-time
docker-compose logs web Show logs for web service only
docker-compose logs --tail=50 Show last 50 log lines

Notes:

Colors help distinguish between different services

docker-compose exec

Docker Compose

Execute commands in running service containers

Syntax:

docker-compose exec [OPTIONS] SERVICE COMMAND [ARGS...]

Examples:

docker-compose exec web bash Open bash shell in web service
docker-compose exec db mysql -u root -p Connect to MySQL in db service
docker-compose exec web python manage.py migrate Run Django migrations

Notes:

Service must be running to use exec

docker-compose build

Docker Compose

Build or rebuild services

Syntax:

docker-compose build [OPTIONS] [SERVICE...]

Examples:

docker-compose build Build all services
docker-compose build web Build only web service
docker-compose build --no-cache Build without cache
docker-compose build --parallel Build services in parallel

Notes:

Only builds services that have a 'build' configuration

FROM

Dockerfile

Set base image for the build

Syntax:

FROM [--platform=<platform>] <image>[:<tag>] [AS <name>]

Examples:

FROM ubuntu:20.04 Use Ubuntu 20.04 as base
FROM node:16-alpine Use Node.js 16 on Alpine Linux
FROM python:3.9 AS builder Multi-stage build with alias
FROM --platform=linux/amd64 ubuntu Specify platform

Notes:

Must be the first instruction in Dockerfile (except ARG for FROM)

RUN

Dockerfile

Execute commands during image build

Syntax:

RUN <command> (shell form) or RUN ["executable", "param1", "param2"] (exec form)

Examples:

RUN apt-get update && apt-get install -y curl Install packages on Ubuntu
RUN ["npm", "install"] Exec form command
RUN pip install -r requirements.txt Install Python dependencies
RUN mkdir -p /app/data Create directories

Notes:

Each RUN creates a new layer; combine commands with && to reduce layers

COPY

Dockerfile

Copy files from build context to image

Syntax:

COPY [--chown=<user>:<group>] <src>... <dest>

Examples:

COPY . /app Copy current directory to /app
COPY requirements.txt /app/ Copy specific file
COPY --chown=www-data:www-data . /var/www Copy with ownership
COPY ["app.js", "package.json", "/app/"] Copy multiple files

Notes:

Preferred over ADD for simple file copying

ADD

Dockerfile

Copy files with additional features (URLs, tar extraction)

Syntax:

ADD [--chown=<user>:<group>] <src>... <dest>

Examples:

ADD https://example.com/file.tar.gz /tmp/ Download file from URL
ADD archive.tar.gz /app/ Extract tar archive
ADD --chown=1000:1000 . /app Add with specific ownership

Notes:

Automatically extracts tar files and can fetch URLs; use COPY for simple copying

WORKDIR

Dockerfile

Set working directory for subsequent instructions

Syntax:

WORKDIR /path/to/workdir

Examples:

WORKDIR /app Set working directory to /app
WORKDIR $HOME/myapp Use environment variable
WORKDIR /app\nRUN npm install Set workdir then run command

Notes:

Creates directory if it doesn't exist; affects RUN, CMD, ENTRYPOINT, COPY, ADD

ENV

Dockerfile

Set environment variables

Syntax:

ENV <key>=<value> ... or ENV <key> <value>

Examples:

ENV NODE_ENV=production Set Node.js environment
ENV PATH=$PATH:/app/bin Extend PATH variable
ENV DB_HOST=localhost DB_PORT=5432 Set multiple variables

Notes:

Variables persist in running containers and can be overridden

EXPOSE

Dockerfile

Inform Docker about container port usage

Syntax:

EXPOSE <port> [<port>/<protocol>...]

Examples:

EXPOSE 80 Expose HTTP port
EXPOSE 443 80 Expose multiple ports
EXPOSE 8080/tcp 8080/udp Specify protocol

Notes:

Documentary instruction; doesn't actually publish ports

CMD

Dockerfile

Provide default command for container execution

Syntax:

CMD ["executable","param1","param2"] (exec form)

Examples:

CMD ["nginx", "-g", "daemon off;"] Start nginx (exec form)
CMD npm start Start app (shell form)
CMD ["python", "app.py"] Run Python application

Notes:

Only last CMD takes effect; can be overridden by docker run arguments

ENTRYPOINT

Dockerfile

Configure container to run as executable

Syntax:

ENTRYPOINT ["executable", "param1", "param2"] (exec form)

Examples:

ENTRYPOINT ["./docker-entrypoint.sh"] Use shell script as entrypoint
ENTRYPOINT ["python", "app.py"] Python app entrypoint
ENTRYPOINT ["nginx", "-g", "daemon off;"]\nCMD ["-c", "/etc/nginx/nginx.conf"] ENTRYPOINT with CMD defaults

Notes:

Cannot be overridden by docker run arguments; combines with CMD

docker network ls

Networking

List Docker networks

Syntax:

docker network ls [OPTIONS]

Examples:

docker network ls List all networks
docker network ls --filter driver=bridge List only bridge networks
docker network ls -q List only network IDs

Notes:

Shows built-in networks (bridge, host, none) and custom networks

docker network create

Networking

Create a Docker network

Syntax:

docker network create [OPTIONS] NETWORK

Examples:

docker network create mynetwork Create bridge network
docker network create --driver bridge mynetwork Explicitly specify bridge driver
docker network create --subnet=172.20.0.0/16 mynetwork Create with custom subnet
docker network create --internal mynetwork Create internal-only network

Notes:

Default driver is bridge; containers on same network can communicate

docker network connect

Networking

Connect container to network

Syntax:

docker network connect [OPTIONS] NETWORK CONTAINER

Examples:

docker network connect mynetwork mycontainer Connect container to network
docker network connect --ip 172.20.0.10 mynetwork mycontainer Connect with specific IP
docker network connect --alias web mynetwork mycontainer Connect with network alias

Notes:

Container can be connected to multiple networks simultaneously

docker network disconnect

Networking

Disconnect container from network

Syntax:

docker network disconnect [OPTIONS] NETWORK CONTAINER

Examples:

docker network disconnect mynetwork mycontainer Disconnect container from network
docker network disconnect -f mynetwork mycontainer Force disconnect

Notes:

Cannot disconnect from default bridge network while container is running

docker network inspect

Networking

Display detailed network information

Syntax:

docker network inspect [OPTIONS] NETWORK [NETWORK...]

Examples:

docker network inspect mynetwork Show network details
docker network inspect --format '{{.IPAM.Config}}' mynetwork Show IP configuration

Notes:

Returns JSON with network configuration and connected containers

docker network rm

Networking

Remove Docker networks

Syntax:

docker network rm NETWORK [NETWORK...]

Examples:

docker network rm mynetwork Remove network
docker network rm $(docker network ls -q) Remove all custom networks

Notes:

Cannot remove networks with connected containers

docker volume ls

Volumes & Storage

List Docker volumes

Syntax:

docker volume ls [OPTIONS]

Examples:

docker volume ls List all volumes
docker volume ls -f dangling=true List unused volumes
docker volume ls -q List only volume names

Notes:

Shows both named volumes and anonymous volumes

docker volume create

Volumes & Storage

Create a Docker volume

Syntax:

docker volume create [OPTIONS] [VOLUME]

Examples:

docker volume create myvolume Create named volume
docker volume create --driver local myvolume Specify volume driver
docker volume create --opt type=nfs --opt device=:/path myvolume Create NFS volume

Notes:

Volumes persist data independent of container lifecycle

docker volume inspect

Volumes & Storage

Display detailed volume information

Syntax:

docker volume inspect [OPTIONS] VOLUME [VOLUME...]

Examples:

docker volume inspect myvolume Show volume details
docker volume inspect --format '{{.Mountpoint}}' myvolume Show volume path

Notes:

Returns JSON with volume configuration and mount information

docker volume rm

Volumes & Storage

Remove Docker volumes

Syntax:

docker volume rm [OPTIONS] VOLUME [VOLUME...]

Examples:

docker volume rm myvolume Remove volume
docker volume rm -f myvolume Force remove volume
docker volume rm $(docker volume ls -q) Remove all volumes

Notes:

Cannot remove volumes in use by containers

docker volume prune

Volumes & Storage

Remove unused volumes

Syntax:

docker volume prune [OPTIONS]

Examples:

docker volume prune Remove all unused volumes
docker volume prune -f Remove without confirmation
docker volume prune --filter 'label!=keep' Remove with filter

Notes:

Removes all volumes not referenced by any containers

docker system info

Troubleshooting

Display system-wide information

Syntax:

docker system info [OPTIONS]

Examples:

docker system info Show detailed system information
docker system info --format '{{.ServerVersion}}' Show specific info

Notes:

Same as 'docker info' - shows containers, images, storage driver info

docker system df

Troubleshooting

Show Docker disk usage

Syntax:

docker system df [OPTIONS]

Examples:

docker system df Show disk usage summary
docker system df -v Show detailed disk usage

Notes:

Displays space used by images, containers, volumes, and cache

docker system prune

Troubleshooting

Remove unused Docker objects

Syntax:

docker system prune [OPTIONS]

Examples:

docker system prune Remove unused containers, images, networks
docker system prune -a Remove all unused images (not just dangling)
docker system prune --volumes Also remove unused volumes
docker system prune -f Remove without confirmation

Notes:

Great for cleaning up and reclaiming disk space

docker system events

Troubleshooting

Get real-time events from server

Syntax:

docker system events [OPTIONS]

Examples:

docker system events Monitor all Docker events
docker system events --filter container=mycontainer Monitor specific container
docker system events --since '2023-01-01' Show events since date
docker system events --format '{{.Type}}: {{.Action}}' Custom event format

Notes:

Useful for debugging and monitoring Docker activity

docker top

Troubleshooting

Display running processes in container

Syntax:

docker top CONTAINER [ps OPTIONS]

Examples:

docker top mycontainer Show processes in container
docker top mycontainer aux Show detailed process info
docker top mycontainer -eo pid,comm Show specific columns

Notes:

Shows processes from the host's perspective

docker diff

Troubleshooting

Inspect changes to container filesystem

Syntax:

docker diff CONTAINER

Examples:

docker diff mycontainer Show filesystem changes

Notes:

A=added, D=deleted, C=changed files since container creation

docker port

Troubleshooting

List port mappings for container

Syntax:

docker port CONTAINER [PRIVATE_PORT[/PROTO]]

Examples:

docker port mycontainer Show all port mappings
docker port mycontainer 80 Show mapping for port 80
docker port mycontainer 80/tcp Show TCP mapping for port 80

Notes:

Shows how container ports are mapped to host ports

🐳 What is Docker?

Docker is a containerization platform that enables developers to package applications and their dependencies into lightweight, portable containers. Created by Solomon Hykes in 2013, Docker revolutionized software deployment by solving the "it works on my machine" problem through consistent, isolated environments that run anywhere.

🚀 Core Features

  • Containerization: Lightweight alternative to virtual machines
  • Portability: Run anywhere - development, testing, production
  • Scalability: Easy horizontal scaling and orchestration
  • Efficiency: Share host OS kernel, minimal overhead
  • Version control: Image versioning and rollback capabilities
  • Isolation: Secure separation between applications

💡 Why Use Docker?

  • Consistency: Identical environments across all stages
  • Speed: Fast startup times and deployment
  • Resource efficiency: Better utilization than VMs
  • DevOps integration: Perfect for CI/CD pipelines
  • Microservices: Ideal for modern application architecture
  • Easy rollbacks: Quick deployment and version management

🌟 Key Docker Concepts

Container

A running instance of a Docker image. Lightweight, standalone executable package that includes everything needed to run an application.

Image

Read-only template used to create containers. Built from a Dockerfile and contains the application code, runtime, and dependencies.

Dockerfile

Text file containing instructions to build a Docker image. Defines the environment, dependencies, and commands needed.

Registry

Storage and distribution system for Docker images. Docker Hub is the default public registry, but private registries are also common.

Volume

Persistent data storage that exists outside the container lifecycle. Volumes can be shared between containers.

Network

Virtual networks that allow containers to communicate with each other and external services securely.

🔄 Docker Workflow

1. Build

Create Docker image from Dockerfile

docker build -t myapp .

2. Ship

Push image to registry

docker push myapp

3. Pull

Download image from registry

docker pull myapp

4. Run

Start container from image

docker run myapp

Development Cycle: Write Code → Build Image → Test Container → Deploy to Production

🏗️ Docker vs Virtual Machines

Docker Containers

  • • Share host OS kernel
  • • Lightweight (MBs in size)
  • • Fast startup (seconds)
  • • Higher density per host
  • • Process-level isolation
  • • Less resource overhead

Virtual Machines

  • • Each VM has full OS
  • • Heavy (GBs in size)
  • • Slower startup (minutes)
  • • Lower density per host
  • • Hardware-level isolation
  • • Higher resource overhead

🛠️ Docker Ecosystem

Core Tools

  • Docker Engine: Core containerization runtime
  • Docker Compose: Multi-container application orchestration
  • Docker Hub: Cloud-based registry service
  • Docker Desktop: GUI application for development
  • Docker Swarm: Native clustering solution

Integration Partners

  • Kubernetes: Advanced container orchestration
  • Jenkins: CI/CD pipeline integration
  • AWS/Azure/GCP: Cloud platform support
  • GitLab/GitHub: Source code and registry integration
  • Monitoring: Prometheus, Grafana, ELK stack

🚀 Getting Started with Docker

1. Installation

Download Docker Desktop from docker.com • Available for Windows, macOS, and Linux • Includes Docker Engine, CLI, and Compose

2. First Container

docker run hello-world • Verify installation and pull your first image

3. Create Dockerfile

Write simple Dockerfile • Build your first image • Practice with common base images like Ubuntu, Node.js, or Python

⚡ Docker Use Cases

Development

  • • Consistent dev environments
  • • Easy onboarding for new developers
  • • Isolate different project dependencies
  • • Quick testing of different versions

Production

  • • Microservices architecture
  • • Auto-scaling applications
  • • Zero-downtime deployments
  • • Infrastructure as Code

Testing

  • • Integration testing environments
  • • Automated testing pipelines
  • • Clean test data isolation
  • • Performance testing at scale

Docker Revolution: Docker has fundamentally changed how we build, ship, and run applications. From development to production, it provides consistency, efficiency, and scalability. This cheat sheet is your guide to mastering Docker commands and concepts! 🐳

Pro Docker Tips

Essential Docker Workflow

  1. docker build -t myapp . - Build your application image
  2. docker run -d -p 8080:80 myapp - Run container in background
  3. docker ps - Check running containers
  4. docker logs myapp - View application logs
  5. docker exec -it myapp bash - Debug inside container
  6. docker stop myapp - Stop when done

Docker Best Practices

  • Use specific image tags, avoid latest
  • Create optimized Dockerfiles with multi-stage builds
  • Use .dockerignore to exclude unnecessary files
  • Run containers as non-root users for security
  • Use volumes for persistent data storage
  • Regularly clean up with docker system prune