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.
📚 Practice what you've learned with our Docker Flashcards
docker version
Setup & InstallationDisplay Docker version information
Syntax:
docker version [OPTIONS]Examples:
docker version Show Docker version infodocker version --format '{{.Server.Version}}' Show only server versiondocker --version Short version displayNotes:
Useful for checking Docker installation and client/server versions
docker info
Setup & InstallationDisplay system-wide information
Syntax:
docker info [OPTIONS]Examples:
docker info Show detailed system informationdocker info --format '{{.ContainersRunning}}' Show only running containers countdocker info | grep 'Storage Driver' Check storage driverNotes:
Shows containers, images, storage driver, and kernel version
docker login
Setup & InstallationLog in to a Docker registry
Syntax:
docker login [SERVER]Examples:
docker login Log in to Docker Hubdocker login registry.example.com Log in to private registrydocker login -u username Log in with specific usernameNotes:
Credentials are stored in ~/.docker/config.json
docker logout
Setup & InstallationLog out from a Docker registry
Syntax:
docker logout [SERVER]Examples:
docker logout Log out from Docker Hubdocker logout registry.example.com Log out from private registryNotes:
Removes stored credentials from config file
docker run
Container ManagementCreate and start a new container
Syntax:
docker run [OPTIONS] IMAGE [COMMAND] [ARG...]Examples:
docker run hello-world Run hello-world containerdocker run -it ubuntu bash Run Ubuntu interactivelydocker run -d -p 8080:80 nginx Run nginx in background on port 8080docker run --name mycontainer nginx Run with custom namedocker run -v /host/path:/container/path nginx Run with volume mountdocker run --rm alpine echo 'Hello World' Run and auto-remove after exitNotes:
Most commonly used Docker command for creating containers
docker ps
Container ManagementList running containers
Syntax:
docker ps [OPTIONS]Examples:
docker ps List running containersdocker ps -a List all containers (including stopped)docker ps -q List only container IDsdocker ps --filter 'status=exited' List only exited containersdocker ps --format 'table {{.Names}}\t{{.Status}}' Custom output formatNotes:
Use -a to see all containers, not just running ones
docker start
Container ManagementStart stopped containers
Syntax:
docker start [OPTIONS] CONTAINER [CONTAINER...]Examples:
docker start mycontainer Start container by namedocker start 1a2b3c4d Start container by IDdocker start -a mycontainer Start and attach to containerdocker start $(docker ps -aq) Start all stopped containersNotes:
Containers retain their configuration from when they were created
docker stop
Container ManagementStop running containers
Syntax:
docker stop [OPTIONS] CONTAINER [CONTAINER...]Examples:
docker stop mycontainer Stop container by namedocker stop 1a2b3c4d Stop container by IDdocker stop -t 30 mycontainer Stop with 30 second timeoutdocker stop $(docker ps -q) Stop all running containersNotes:
Sends SIGTERM, then SIGKILL after timeout (default 10s)
docker restart
Container ManagementRestart containers
Syntax:
docker restart [OPTIONS] CONTAINER [CONTAINER...]Examples:
docker restart mycontainer Restart container by namedocker restart -t 30 mycontainer Restart with custom timeoutdocker restart $(docker ps -aq) Restart all containersNotes:
Equivalent to running docker stop followed by docker start
docker rm
Container ManagementRemove containers
Syntax:
docker rm [OPTIONS] CONTAINER [CONTAINER...]Examples:
docker rm mycontainer Remove container by namedocker rm -f mycontainer Force remove running containerdocker rm $(docker ps -aq) Remove all containersdocker rm $(docker ps -f status=exited -q) Remove all exited containersNotes:
Container must be stopped first unless using -f flag
docker exec
Container ManagementExecute commands in running containers
Syntax:
docker exec [OPTIONS] CONTAINER COMMAND [ARG...]Examples:
docker exec -it mycontainer bash Open interactive bash shelldocker exec mycontainer ls -la List files in containerdocker exec -u root mycontainer apt update Run command as root userdocker exec -w /app mycontainer pwd Run command in specific directoryNotes:
Container must be running to use exec
docker logs
Container ManagementFetch container logs
Syntax:
docker logs [OPTIONS] CONTAINERExamples:
docker logs mycontainer Show all logsdocker logs -f mycontainer Follow log output in real-timedocker logs --tail 50 mycontainer Show last 50 linesdocker logs --since 2h mycontainer Show logs from last 2 hoursdocker logs -t mycontainer Show timestampsNotes:
Only shows logs from STDOUT and STDERR
docker inspect
Container ManagementDisplay detailed container information
Syntax:
docker inspect [OPTIONS] NAME|ID [NAME|ID...]Examples:
docker inspect mycontainer Show full container detailsdocker inspect --format '{{.NetworkSettings.IPAddress}}' mycontainer Show container IP addressdocker inspect --format '{{.State.Status}}' mycontainer Show container statusdocker inspect --format '{{.Config.Image}}' mycontainer Show container imageNotes:
Returns JSON data with comprehensive container information
docker stats
Container ManagementDisplay live resource usage statistics
Syntax:
docker stats [OPTIONS] [CONTAINER...]Examples:
docker stats Show stats for all running containersdocker stats mycontainer Show stats for specific containerdocker stats --no-stream Show stats once and exitdocker stats --format 'table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}' Custom stats formatNotes:
Shows CPU, memory, network, and block I/O usage in real-time
docker build
Image OperationsBuild Docker images from Dockerfile
Syntax:
docker build [OPTIONS] PATH | URL | -Examples:
docker build . Build image from current directorydocker build -t myapp:latest . Build and tag imagedocker build -f Dockerfile.prod . Use specific Dockerfiledocker build --no-cache . Build without using cachedocker build --build-arg VERSION=1.0 . Pass build argumentsNotes:
Dockerfile must be in the build context (usually current directory)
docker images
Image OperationsList Docker images
Syntax:
docker images [OPTIONS] [REPOSITORY[:TAG]]Examples:
docker images List all imagesdocker images -a Show all images including intermediatesdocker images -q Show only image IDsdocker images --filter 'dangling=true' Show dangling imagesdocker images --format 'table {{.Repository}}\t{{.Tag}}\t{{.Size}}' Custom formatNotes:
Use 'docker image ls' as modern alternative
docker pull
Image OperationsDownload images from registry
Syntax:
docker pull [OPTIONS] NAME[:TAG|@DIGEST]Examples:
docker pull ubuntu Pull latest Ubuntu imagedocker pull ubuntu:20.04 Pull specific Ubuntu versiondocker pull --all-tags ubuntu Pull all tags for Ubuntudocker pull registry.example.com/myapp Pull from private registryNotes:
Defaults to 'latest' tag if no tag specified
docker push
Image OperationsUpload images to registry
Syntax:
docker push [OPTIONS] NAME[:TAG]Examples:
docker push myusername/myapp Push to Docker Hubdocker push myusername/myapp:v1.0 Push specific tagdocker push registry.example.com/myapp Push to private registryNotes:
Image must be tagged appropriately before pushing
docker rmi
Image OperationsRemove Docker images
Syntax:
docker rmi [OPTIONS] IMAGE [IMAGE...]Examples:
docker rmi myimage Remove image by namedocker rmi -f myimage Force remove imagedocker rmi $(docker images -q) Remove all imagesdocker rmi $(docker images -f dangling=true -q) Remove dangling imagesNotes:
Cannot remove images being used by containers unless forced
docker tag
Image OperationsTag images with new names
Syntax:
docker tag SOURCE_IMAGE[:TAG] TARGET_IMAGE[:TAG]Examples:
docker tag myapp myapp:v1.0 Add version tagdocker tag myapp:latest myusername/myapp:latest Tag for Docker Hubdocker tag local-image registry.example.com/myapp Tag for private registryNotes:
Creates a new reference to existing image data
docker save
Image OperationsSave images to tar archive
Syntax:
docker save [OPTIONS] IMAGE [IMAGE...]Examples:
docker save myapp > myapp.tar Save image to tar filedocker save -o myapp.tar myapp Save using output flagdocker save myapp:v1 myapp:v2 > myapp-versions.tar Save multiple tagsNotes:
Useful for offline image distribution
docker load
Image OperationsLoad images from tar archive
Syntax:
docker load [OPTIONS]Examples:
docker load < myapp.tar Load image from tar filedocker load -i myapp.tar Load using input flagdocker load --quiet < myapp.tar Load without verbose outputNotes:
Restores images saved with docker save
docker history
Image OperationsShow image layer history
Syntax:
docker history [OPTIONS] IMAGEExamples:
docker history myapp Show image build historydocker history --no-trunc myapp Show full command historydocker history -q myapp Show only layer IDsNotes:
Displays the commands used to create each layer
docker-compose up
Docker ComposeCreate and start containers defined in docker-compose.yml
Syntax:
docker-compose up [OPTIONS] [SERVICE...]Examples:
docker-compose up Start all servicesdocker-compose up -d Start services in backgrounddocker-compose up --build Rebuild images before startingdocker-compose up web Start only web servicedocker-compose up --scale web=3 Start 3 instances of web serviceNotes:
Looks for docker-compose.yml in current directory
docker-compose down
Docker ComposeStop and remove containers, networks
Syntax:
docker-compose down [OPTIONS]Examples:
docker-compose down Stop and remove containersdocker-compose down -v Also remove volumesdocker-compose down --rmi all Also remove all imagesdocker-compose down --remove-orphans Remove orphaned containersNotes:
Stops containers and removes containers, networks, volumes, and images
docker-compose ps
Docker ComposeList containers for the project
Syntax:
docker-compose ps [OPTIONS] [SERVICE...]Examples:
docker-compose ps List all project containersdocker-compose ps -q List only container IDsdocker-compose ps web List containers for web service onlyNotes:
Shows containers created by current docker-compose.yml
docker-compose logs
Docker ComposeView output from containers
Syntax:
docker-compose logs [OPTIONS] [SERVICE...]Examples:
docker-compose logs Show logs for all servicesdocker-compose logs -f Follow logs in real-timedocker-compose logs web Show logs for web service onlydocker-compose logs --tail=50 Show last 50 log linesNotes:
Colors help distinguish between different services
docker-compose exec
Docker ComposeExecute commands in running service containers
Syntax:
docker-compose exec [OPTIONS] SERVICE COMMAND [ARGS...]Examples:
docker-compose exec web bash Open bash shell in web servicedocker-compose exec db mysql -u root -p Connect to MySQL in db servicedocker-compose exec web python manage.py migrate Run Django migrationsNotes:
Service must be running to use exec
docker-compose build
Docker ComposeBuild or rebuild services
Syntax:
docker-compose build [OPTIONS] [SERVICE...]Examples:
docker-compose build Build all servicesdocker-compose build web Build only web servicedocker-compose build --no-cache Build without cachedocker-compose build --parallel Build services in parallelNotes:
Only builds services that have a 'build' configuration
FROM
DockerfileSet base image for the build
Syntax:
FROM [--platform=<platform>] <image>[:<tag>] [AS <name>]Examples:
FROM ubuntu:20.04 Use Ubuntu 20.04 as baseFROM node:16-alpine Use Node.js 16 on Alpine LinuxFROM python:3.9 AS builder Multi-stage build with aliasFROM --platform=linux/amd64 ubuntu Specify platformNotes:
Must be the first instruction in Dockerfile (except ARG for FROM)
RUN
DockerfileExecute 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 UbuntuRUN ["npm", "install"] Exec form commandRUN pip install -r requirements.txt Install Python dependenciesRUN mkdir -p /app/data Create directoriesNotes:
Each RUN creates a new layer; combine commands with && to reduce layers
COPY
DockerfileCopy files from build context to image
Syntax:
COPY [--chown=<user>:<group>] <src>... <dest>Examples:
COPY . /app Copy current directory to /appCOPY requirements.txt /app/ Copy specific fileCOPY --chown=www-data:www-data . /var/www Copy with ownershipCOPY ["app.js", "package.json", "/app/"] Copy multiple filesNotes:
Preferred over ADD for simple file copying
ADD
DockerfileCopy 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 URLADD archive.tar.gz /app/ Extract tar archiveADD --chown=1000:1000 . /app Add with specific ownershipNotes:
Automatically extracts tar files and can fetch URLs; use COPY for simple copying
WORKDIR
DockerfileSet working directory for subsequent instructions
Syntax:
WORKDIR /path/to/workdirExamples:
WORKDIR /app Set working directory to /appWORKDIR $HOME/myapp Use environment variableWORKDIR /app\nRUN npm install Set workdir then run commandNotes:
Creates directory if it doesn't exist; affects RUN, CMD, ENTRYPOINT, COPY, ADD
ENV
DockerfileSet environment variables
Syntax:
ENV <key>=<value> ... or ENV <key> <value>Examples:
ENV NODE_ENV=production Set Node.js environmentENV PATH=$PATH:/app/bin Extend PATH variableENV DB_HOST=localhost DB_PORT=5432 Set multiple variablesNotes:
Variables persist in running containers and can be overridden
EXPOSE
DockerfileInform Docker about container port usage
Syntax:
EXPOSE <port> [<port>/<protocol>...]Examples:
EXPOSE 80 Expose HTTP portEXPOSE 443 80 Expose multiple portsEXPOSE 8080/tcp 8080/udp Specify protocolNotes:
Documentary instruction; doesn't actually publish ports
CMD
DockerfileProvide 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 applicationNotes:
Only last CMD takes effect; can be overridden by docker run arguments
ENTRYPOINT
DockerfileConfigure container to run as executable
Syntax:
ENTRYPOINT ["executable", "param1", "param2"] (exec form)Examples:
ENTRYPOINT ["./docker-entrypoint.sh"] Use shell script as entrypointENTRYPOINT ["python", "app.py"] Python app entrypointENTRYPOINT ["nginx", "-g", "daemon off;"]\nCMD ["-c", "/etc/nginx/nginx.conf"] ENTRYPOINT with CMD defaultsNotes:
Cannot be overridden by docker run arguments; combines with CMD
docker network ls
NetworkingList Docker networks
Syntax:
docker network ls [OPTIONS]Examples:
docker network ls List all networksdocker network ls --filter driver=bridge List only bridge networksdocker network ls -q List only network IDsNotes:
Shows built-in networks (bridge, host, none) and custom networks
docker network create
NetworkingCreate a Docker network
Syntax:
docker network create [OPTIONS] NETWORKExamples:
docker network create mynetwork Create bridge networkdocker network create --driver bridge mynetwork Explicitly specify bridge driverdocker network create --subnet=172.20.0.0/16 mynetwork Create with custom subnetdocker network create --internal mynetwork Create internal-only networkNotes:
Default driver is bridge; containers on same network can communicate
docker network connect
NetworkingConnect container to network
Syntax:
docker network connect [OPTIONS] NETWORK CONTAINERExamples:
docker network connect mynetwork mycontainer Connect container to networkdocker network connect --ip 172.20.0.10 mynetwork mycontainer Connect with specific IPdocker network connect --alias web mynetwork mycontainer Connect with network aliasNotes:
Container can be connected to multiple networks simultaneously
docker network disconnect
NetworkingDisconnect container from network
Syntax:
docker network disconnect [OPTIONS] NETWORK CONTAINERExamples:
docker network disconnect mynetwork mycontainer Disconnect container from networkdocker network disconnect -f mynetwork mycontainer Force disconnectNotes:
Cannot disconnect from default bridge network while container is running
docker network inspect
NetworkingDisplay detailed network information
Syntax:
docker network inspect [OPTIONS] NETWORK [NETWORK...]Examples:
docker network inspect mynetwork Show network detailsdocker network inspect --format '{{.IPAM.Config}}' mynetwork Show IP configurationNotes:
Returns JSON with network configuration and connected containers
docker network rm
NetworkingRemove Docker networks
Syntax:
docker network rm NETWORK [NETWORK...]Examples:
docker network rm mynetwork Remove networkdocker network rm $(docker network ls -q) Remove all custom networksNotes:
Cannot remove networks with connected containers
docker volume ls
Volumes & StorageList Docker volumes
Syntax:
docker volume ls [OPTIONS]Examples:
docker volume ls List all volumesdocker volume ls -f dangling=true List unused volumesdocker volume ls -q List only volume namesNotes:
Shows both named volumes and anonymous volumes
docker volume create
Volumes & StorageCreate a Docker volume
Syntax:
docker volume create [OPTIONS] [VOLUME]Examples:
docker volume create myvolume Create named volumedocker volume create --driver local myvolume Specify volume driverdocker volume create --opt type=nfs --opt device=:/path myvolume Create NFS volumeNotes:
Volumes persist data independent of container lifecycle
docker volume inspect
Volumes & StorageDisplay detailed volume information
Syntax:
docker volume inspect [OPTIONS] VOLUME [VOLUME...]Examples:
docker volume inspect myvolume Show volume detailsdocker volume inspect --format '{{.Mountpoint}}' myvolume Show volume pathNotes:
Returns JSON with volume configuration and mount information
docker volume rm
Volumes & StorageRemove Docker volumes
Syntax:
docker volume rm [OPTIONS] VOLUME [VOLUME...]Examples:
docker volume rm myvolume Remove volumedocker volume rm -f myvolume Force remove volumedocker volume rm $(docker volume ls -q) Remove all volumesNotes:
Cannot remove volumes in use by containers
docker volume prune
Volumes & StorageRemove unused volumes
Syntax:
docker volume prune [OPTIONS]Examples:
docker volume prune Remove all unused volumesdocker volume prune -f Remove without confirmationdocker volume prune --filter 'label!=keep' Remove with filterNotes:
Removes all volumes not referenced by any containers
docker system info
TroubleshootingDisplay system-wide information
Syntax:
docker system info [OPTIONS]Examples:
docker system info Show detailed system informationdocker system info --format '{{.ServerVersion}}' Show specific infoNotes:
Same as 'docker info' - shows containers, images, storage driver info
docker system df
TroubleshootingShow Docker disk usage
Syntax:
docker system df [OPTIONS]Examples:
docker system df Show disk usage summarydocker system df -v Show detailed disk usageNotes:
Displays space used by images, containers, volumes, and cache
docker system prune
TroubleshootingRemove unused Docker objects
Syntax:
docker system prune [OPTIONS]Examples:
docker system prune Remove unused containers, images, networksdocker system prune -a Remove all unused images (not just dangling)docker system prune --volumes Also remove unused volumesdocker system prune -f Remove without confirmationNotes:
Great for cleaning up and reclaiming disk space
docker system events
TroubleshootingGet real-time events from server
Syntax:
docker system events [OPTIONS]Examples:
docker system events Monitor all Docker eventsdocker system events --filter container=mycontainer Monitor specific containerdocker system events --since '2023-01-01' Show events since datedocker system events --format '{{.Type}}: {{.Action}}' Custom event formatNotes:
Useful for debugging and monitoring Docker activity
docker top
TroubleshootingDisplay running processes in container
Syntax:
docker top CONTAINER [ps OPTIONS]Examples:
docker top mycontainer Show processes in containerdocker top mycontainer aux Show detailed process infodocker top mycontainer -eo pid,comm Show specific columnsNotes:
Shows processes from the host's perspective
docker diff
TroubleshootingInspect changes to container filesystem
Syntax:
docker diff CONTAINERExamples:
docker diff mycontainer Show filesystem changesNotes:
A=added, D=deleted, C=changed files since container creation
docker port
TroubleshootingList port mappings for container
Syntax:
docker port CONTAINER [PRIVATE_PORT[/PROTO]]Examples:
docker port mycontainer Show all port mappingsdocker port mycontainer 80 Show mapping for port 80docker port mycontainer 80/tcp Show TCP mapping for port 80Notes:
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 myapp3. Pull
Download image from registry
docker pull myapp4. Run
Start container from image
docker run myappDevelopment 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
docker build -t myapp .- Build your application imagedocker run -d -p 8080:80 myapp- Run container in backgrounddocker ps- Check running containersdocker logs myapp- View application logsdocker exec -it myapp bash- Debug inside containerdocker stop myapp- Stop when done
Docker Best Practices
- Use specific image tags, avoid
latest - Create optimized Dockerfiles with multi-stage builds
- Use
.dockerignoreto exclude unnecessary files - Run containers as non-root users for security
- Use volumes for persistent data storage
- Regularly clean up with
docker system prune