Docker Cheat Sheet & Reference

Docker Cheat Sheet & Reference

This guide is part of the “Cheat Sheets & References for Developers & Engineers” series. This series is designed to provide comprehensive references for popular technologies!

Welcome to our Docker Cheat Sheet & Reference page! This page serves as a comprehensive guide to help you quickly and easily navigate through the most commonly used Docker commands, options, and best practices.

Whether you're new to Docker or an experienced user, our cheat sheet is designed to provide you with a quick reference guide to help you easily manage your Docker environment. So whether you're building and deploying applications, managing containers, or working with Docker images, our cheat sheet has got you covered!

# Getting Started

create & run

Create a container and run it in the background

$ docker run -d -p 80:80 docker/getting-started
  • -d - Run the container in detached (background) mode
  • -p 80:80 - Map port 80 to port 80 in the container, format: host port: container port
  • docker/getting-started - the mirror to use

Create and run the container in the foreground (if you want to exit the container but not close the container, press Ctrl+P+Q)

$ docker run -it --rm -p 8001:8080 --name my-nginx nginx
  • -it - Interactive bash mode
  • --rm - Automatically delete container files after the container terminates
  • -p 8001:8080 - maps 8001the port to 8080the port in the container
  • --name my-nginx - specify a name
  • nginx - the mirror to use

general commands

docker psList running containers
docker ps -aList all containers
docker ps -sList running containers with CPU/memory usage statistics
docker imagesList all available mirrors
docker exec -it <container> bashConnect to a running container using bash shell
docker logs <container>Show the console log of a container
docker stop <container>Stop a running container
docker restart <container>Restart a running container
docker rm <container>Remove a container
docker port <container>Show the port mapping of a container
docker top <container>List the processes running in a container
docker kill <container>Forcefully stop a running container
parameter <container>Can be either the container id or name

# Container Management

start & stop

docker start <container>Start the container
docker stop <container>Stop the container
docker restart <container>Restart the container
docker pause <container>Pause the container
docker unpause <container>Unpause the container
docker wait <container>Block until the container stops running
docker kill <container>Send SIGKILL signal to the container
docker attach <container>Attach to the running container

stats

docker psList the running containers
docker ps -aList all containers, including stopped ones
docker logs <container>Show the logs of the container
docker inspect <container>Display detailed information about the container
docker events <container>Show the events related to the container
docker port <container>Show the public port of the container
docker top <container>Display the running processes inside the container
docker stats <container>Show the resource usage of the container
docker diff <container>Show the changes made to the container

create a container

docker create [options] IMAGE
  -a, --attach # Attach standard output/errors
  -i, --interactive # append standard input (interactive)
  -t, --tty # pseudo-terminal pseudo-tty
      --name NAME # Name your image
  -p, --publish 5000:5000 # Port mapping (host:container)
      --expose 5432 # Expose the port to the container 
  -P, --publish-all # Publish all ports
      --link container:alias # link linking
  -v, --volume `pwd`:/app # mount (absolute path required)
  -e, --env NAME=hello # environment variables env vars

example

$ docker create --name my-container -p 8080:80 nginx

control

docker rename <old-name> <new-name>Rename container
docker rm <container>Remove container
docker update --cpu-shares 512 -m 300M <container>Update container

# Docker Images

general

docker imagesList all Docker images
docker pull [image-name]Pull a Docker image from a registry
docker build [options] [path]Build a Docker image from a Dockerfile
docker push [image-name]Push a Docker image to a registry
docker tag [image-name] [new-image-name]Add a new tag to a Docker image
docker rmi [image-name]Remove a Docker image
docker save [image-name] -o [path/to/save]Save a Docker image to a tar archive
docker load -i [path/to/archive]Load a Docker image from a tar archive
docker history [image-name]Show the history of a Docker image
docker inspect [image-name]Display low-level information on a Docker image
docker search [search-term]Search for Docker images on Docker Hub
docker commit [container-name] [new-image-name]Create a new Docker image from a container
docker import [URL] [new-image-name]Create a new Docker image from a remote file
docker image pruneRemove all dangling (unused) images

build image

# Build an image from a Dockerfile located in the current directory
docker build -t my-image .

# Build an image from a Dockerfile located in a specific directory
docker build -t my-image /path/to/Dockerfile/directory

# Build an image with a specific tag
docker build -t my-username/my-image:1.0 .

# Build an image with build arguments
docker build -t my-image --build-arg MY_ARG=value .

# Build an image with a custom Dockerfile name
docker build -t my-image -f Dockerfile.custom .

# Build an image from a Dockerfile located in a specific GitHub repository
docker build github.com/creack/docker-firefox

# Build an image from a Dockerfile passed via STDIN
docker build - < Dockerfile

# Build an image from a context passed via STDIN
docker build - < context.tar.gz

# Build an image with a specific tag
docker build -t eon/nginx-server .

# Build an image from a different Dockerfile than the default
docker build -f myOtherDockerfile .

# Build an image from a remote Dockerfile
curl example.com/remote/Dockerfile | docker build -f - .

remove all

$ docker rmi -f $(docker images | grep "none" | awk '{print $3}')

This command will remove all Docker images on your machine that are not currently being used by any containers. Here's how it works:

  • docker images lists all Docker images on the host machine.
  • grep "none" filters the output to show only images with the tag "none". These images are usually created when a new image is built, and the old image with the same name and tag is still present on the machine.
  • awk '{print $3}' extracts the third column from the output, which is the image ID.
  • $() is a command substitution that passes the output of the previous command as input to docker rmi -f. The -f option forces the removal of the specified image(s).

# Docker Network

operate

docker network lsList all Docker networks
docker network create [network-name]Create a new Docker network
docker network rm [network-name]Remove a Docker network
docker network inspect [network-name]Display detailed information on a Docker network
docker network connect [network-name] [container-name]Connect a container to a Docker network
docker network disconnect [network-name] [container-name]Disconnect a container from a Docker network
docker network pruneRemove all unused Docker networks
docker network create --driver overlay [network-name]Create a Docker swarm overlay network
docker network create --driver bridge --subnet [subnet] [network-name]Create a bridge network with a specified subnet
docker network create --driver macvlan --subnet [subnet] -o parent=[interface-name] [network-name]Create a MAC VLAN network with a specified subnet and parent interface

create a network

docker network create -d overlay OverlayNetwork
docker network create -d bridge BridgeNetwork
docker network create -d overlay \
  --subnet=192.168.0.0/16 \
  --subnet=192.170.0.0/16 \
  --gateway=192.168.0.100 \
  --gateway=192.170.0.100 \
  --ip-range=192.168.1.0/24 \
  --aux-address="my-router=192.168.1.5" \
  --aux-address="my-switch=192.168.1.6" \
  --aux-address="my-printer=192.170.1.5" \
  --aux-address="my-nas=192.170.1.6" \
  OverlayNetwork
  • --subnet - Defines one or more subnets for the network.
  • --gateway - Defines one or more gateways for the network.
  • --ip-range - Defines a range of IP addresses that can be assigned to containers on the network.
  • --aux-address - Defines additional IP addresses that can be assigned to containers on the network.

# Miscellaneous

Docker Hub

docker loginLogin to Docker Hub
docker logoutLogout from Docker Hub
docker search [search-term]Search for Docker images on Docker Hub
docker pull [image-name]Pull a Docker image from Docker Hub
docker push [image-name]Push a Docker image to Docker Hub
docker tag [local-image] [username/image-name:tag]Tag a local Docker image for upload to Docker Hub
docker push [username/image-name:tag]Push a tagged Docker image to Docker Hub
docker build -t [username/image-name:tag] .Build and tag a Docker image with a Dockerfile, then push it to Docker Hub
docker logout [registry]Log out from a specific registry
docker search --filter "is-official=true" [search-term]Search for official Docker images
docker search --filter "is-automated=true" [search-term]Search for automated Docker images
docker system prune -aRemove all unused images and cache on the host machine

Mirror a repository

To log in to the mirror warehouse:

docker login
docker login localhost:8080

To log out of the mirror repository:

docker logout
docker logout localhost:8080

To search for a mirrored image:

docker search nginx
docker search nginx --stars=3 --no-trunc busybox

To pull a mirrored image:

docker pull nginx
docker pull eon01/nginx
docker pull localhost:5000/myadmin/nginx

To push a mirrored image:

docker push eon01/nginx
docker push localhost:5000/myadmin/nginx
 

Docker Compose

docker-compose upCreate and start containers defined in a docker-compose.yml file
docker-compose downStop and remove containers, networks, and volumes created by docker-compose up
docker-compose buildBuild or rebuild services defined in a docker-compose.yml file
docker-compose startStart existing containers defined in a docker-compose.yml file
docker-compose stopStop existing containers defined in a docker-compose.yml file
docker-compose restartRestart containers defined in a docker-compose.yml file
docker-compose logsView output from containers defined in a docker-compose.yml file
docker-compose psList containers defined in a docker-compose.yml file
docker-compose configValidate and view the Compose file
docker-compose pullPull images for services defined in a docker-compose.yml file
docker-compose runRun a one-off command on a service defined in a docker-compose.yml file
docker-compose killForce stop containers defined in a docker-compose.yml file
docker-compose rmRemove stopped containers defined in a docker-compose.yml file
docker-compose execRun a command in a running container
docker-compose up --scale [service-name]=nScale a service to n instances
docker-compose topDisplay the running processes of a container
docker-compose scale <service_name>=<replica>Specify the number of containers for the service
docker-compose run -rm -p 2022:22 web bashStart the web service and run bash as its command, remove the old container
 

Docker Services

docker service createCreate a new Docker service in a Docker Swarm cluster
docker service lsList all Docker services running in a Docker Swarm cluster
docker service inspectDisplay detailed information on a Docker service running in a Docker Swarm cluster
docker service updateUpdate a Docker service running in a Docker Swarm cluster
docker service rmRemove a Docker service running in a Docker Swarm cluster
docker service scaleScale the number of replicas in a Docker service running in a Docker Swarm cluster
docker service logsView the logs of a Docker service running in a Docker Swarm cluster
docker service psList the tasks in a Docker service running in a Docker Swarm cluster
docker service create --networkCreate a Docker service in a specific network in a Docker Swarm cluster
docker service create --replicasCreate a Docker service with a specified number of replicas in a Docker Swarm cluster
docker service create --mountMount a volume to a Docker service running in a Docker Swarm cluster
docker service create --constraintSet placement constraints for a Docker service running in a Docker Swarm cluster
docker service create --envSet environment variables for a Docker service running in a Docker Swarm cluster
docker service create --labelAdd metadata labels to a Docker service running in a Docker Swarm cluster
docker service create --modeSet the update strategy for a Docker service running in a Docker Swarm cluster
docker service create --health-cmdSet a health check command for a Docker service running in a Docker Swarm cluster

Docker Stack

docker stack deployDeploy a new Docker stack
docker stack lsList all Docker stacks
docker stack psList the tasks in a Docker stack
docker stack servicesList the services in a Docker stack
docker stack rmRemove a Docker stack
docker stack deploy --compose-fileDeploy a Docker stack using a Compose file
docker stack deploy --with-registry-authDeploy a Docker stack and authenticate with a private registry
docker stack deploy --pruneRemove any old services that are no longer part of the Docker stack
docker stack deploy --resolve-image alwaysAlways attempt to resolve the latest version of an image
docker stack deploy --orchestrator kubernetesDeploy a Docker stack as a Kubernetes service

Note that some of these commands are specific to Docker Swarm mode, which is a feature of Docker that allows you to run Docker in a clustered mode. Other commands, such as the --orchestrator kubernetes option, are specific to deploying Docker stacks to a Kubernetes cluster.

 

Docker Machine

docker-machine create --driver virtualbox myvm1Create a virtual machine with the VirtualBox driver named myvm1
docker-machine create -d hyperv --hyperv-virtual-switch "myswitch" myvm1Create a virtual machine with the Hyper-V driver named myvm1 using the myswitch virtual switch
docker-machine env myvm1Display basic information about the myvm1 virtual machine
docker-machine ssh myvm1 "docker node ls"List the nodes in your cluster on the myvm1 virtual machine
docker-machine ssh myvm1 "docker node inspect <node ID>"Inspect nodes on the myvm1 virtual machine
docker-machine ssh myvm1 "docker swarm join-token -q worker"View the join token on the myvm1 virtual machine
docker-machine ssh myvm1Open an SSH session with the myvm1 virtual machine; exit the session by typing "exit"
docker-machine ssh myvm2 "docker swarm leave"Let workers leave the swarm on the myvm2 virtual machine
docker-machine ssh myvm1 "docker swarm leave -f"Let the master leave and kill the swarm on the myvm1 virtual machine
docker-machine start myvm1Start the myvm1 virtual machine if it is not running
docker-machine stop $(docker-machine ls -q)Stop all running virtual machines
docker-machine rm $(docker-machine ls -q)Delete all virtual machines and their disk images
docker-machine scp docker-compose.yml myvm1:~Copy the docker-compose.yml file to the home directory of the myvm1 virtual machine
docker-machine ssh myvm1 "docker stack deploy -c <file> <app>"Deploy an application on the myvm1 virtual machine using the specified Compose file and app name
 

Main Commands

attachAttaches local standard input, output, and error streams to a running container
buildBuilds images from Dockerfile
commitCreates a new image from container changes
cpCopies files/folders between the container and the local filesystem
createCreates a new container
diffChecks for changes to files or directories on the container filesystem
eventsGets live events from the server
execRuns a command in the running container
exportExports the container's filesystem to a tar archive
historyShows the history of the image
imagesLists the images
importImports the contents from tarball to create a file system image
infoDisplays system-wide information
inspectReturns low-level information about Docker objects
killKills one or more running containers
loadLoads an image from a tar archive or STDIN
loginLogs in to the Docker registry
logoutLogs out from the Docker registry
logsGets logs of containers
pauseSuspends all processes in one or more containers
portLists the container's port mappings or specific mappings
psLists containers
pullPulls a mirror or repository from the registry
pushPushes the image or repository to the registry
renameRenames a container
restartRestarts one or more containers
rmRemoves one or more containers
rmiRemoves one or more mirrors
runRuns a command in a new container
saveSaves one or more images to a tar archive (streams to STDOUT by default)
searchSearches for images in Docker Hub
startStarts one or more stopped containers
statsShows a live stream of container resource usage statistics
stopStops one or more running containers
tagCreates a tag that references SOURCE_IMAGE TARGET_IMAGE
topDisplays the running processes of a container
unpauseUnpauses all processes in one or more containers
updateUpdates the configuration of one or more containers
versionDisplays Docker version information
waitBlocks until one or more containers stop, then prints their exit codes

Run/Create Options

--add-host list # Add a custom host to the IP map (host:ip)
-a, --attach list # Connect to STDIN, STDOUT or STDERR
    --blkio-weight uint16 # block IO (relative weight), between 10 and 1000, or 0 disabled (default 0)
    --blkio-weight-device list # Block IO weights (relative device weights) (default [])
    --cap-add list # Add Linux functions
    --cap-drop list # Drop Linux functions
    --cgroup-parent string # Optional parent cgroup of the container
    --cgroupns string # The Cgroup namespace to use (host|private)
                        # 'host': cgroup namespace of the Docker host to run the container in
                        # 'private': run the container in its own private cgroup namespace
                        # '': use the 
                        # default-cgroupns-mode option (default)
    --cidfile string # Write the container ID to a file
    --cpu-period int # Limit CPU CFS (Completely Fair Scheduler) periods
    --cpu-quota int # Limit CPU CFS (full fair scheduler) quota
    --cpu-rt-period int # Limit CPU real-time cycles in microseconds
    --cpu-rt-runtime int # Limit CPU realtime runtime in microseconds
-c, --cpu-shares int # CPU shares (relative weights)
    --cpus decimal # Number of CPUs
    --cpuset-cpus string # CPUs allowed to execute (0-3, 0,1)
    --cpuset-mems string # MEMs allowed to execute (0-3, 0,1)
    --device list # Add the host device to the container
    --device-cgroup-rule list # Add the rule to the list of devices allowed by the cgroup
    --device-read-bps list # Limit the read rate (bytes per second) of the device (default [])
    --device-read-iops list # Limit the read rate (IOs per second) of the device (default [])
    --device-write-bps list # Limit the write rate of the device (bytes per second) (default [])
    --device-write-iops list # Limit the write rate of the device (IO per second) (default [])
    --disable-content-trust # Skip image verification (default true)
    --dns list # Set custom DNS servers
    --dns-option list # Set DNS options
    --dns-search list # Set custom DNS search domains
    --domainname string # Container NIS domain name
    --entrypoint string # Override the default entry point of the mirror
--e, --env list # Set environment variables
    --env-file list # Read in environment variable files
    --expose list # expose a port or series of ports
    --gpus gpu-request # GPU devices to add to the container ("all" to pass all GPUs)
    --group-add list # Add other groups to join
    --health-cmd string # Command to run to check operational status
    --health-interval duration # Time (ms|s|m|h) between run checks (default 0s)
    --health-retries int # Need to report unhealthy consecutive failures
    --health-start-period duration # Start time (ms|s|m|h) for container initialization before starting the health retry countdown (default 0s)
    --health-timeout duration # The maximum time (ms|s|m|h) allowed to run a check (default 0s)
    --help # Print the use of
-h, --hostname string # The container host name
    --init # Run an init inside the container to forward signals and harvest processes
--i, --interactive # Keep STDIN open even if there is no connection
    --ip string # IPv4 address (e.g. 172.30.100.104)
    --ip6 string # IPv6 address (e.g., 2001:db8::33)
    --ipc string # The IPC mode to use
    --isolation string # Container isolation technology
    --kernel-memory bytes # Kernel memory limit
-l, --label list # Set metadata on the container
    --label-file list # Read in line delimited label files
    --link list # Add a link to another container
    --link-local-ip list # container IPv4/IPv6 link local address
    --log-driver string # The container's logging driver
    --log-opt list # Logging driver options
    --mac-address string # MAC address of the container (e.g. 92:d0:c6:0a:29:33)
-m, --memory bytes # Memory limit
    --memory-reservation bytes # Memory soft limit
    --memory-swap bytes # Swap limit equal to memory plus swap: '-1' Enable unlimited swap
    --memory-swappiness int # Adjust container memory swapping (0 to 100) (default -1)
    --mount mount # Attach a filesystem mount to the container
    --name string # Assign a name to the container
    --network network # Connect the container to the network
    --network-alias list # Add network-wide aliases to the container
    --no-healthcheck # Disable any container-assigned HEALTHCHECK
    --oom-kill-disable # Disable OOM killers
    --oom-score-adj int # Adjust the host's OOM preferences (-1000 to 1000)
    --pid string # The PID namespace to use
    --pids-limit int # Adjust container pids limit (set -1 for no limit)
    --platform string # Set the platform if the server supports multiple platforms
    --privileged # Grant extended privileges to this container
-p, --publish list # Publish the container's ports to the host
-P, --publish-all # Publish all exposed ports to random ports
    --pull string # Pull mirrors ("always"|"missing"|"never") before creation (default "missing")
    --read-only # Mount the container's root filesystem as read-only
    --restart string # Restart policy to apply when the container exits (default "no")
    --rm # Automatically remove the container when it exits
    --runtime string # Runtime for this container
    --security-opt list # Security options
    --shm-size bytes # size of /dev/shm
    --stop-signal string # Signal to stop the container (default "SIGTERM")
    --stop-timeout int # Timeout to stop the container (in seconds)
    --storage-opt list # Storage driver options for the container
    --sysctl map # Sysctl options (default map[])
    --tmpfs list # Mount tmpfs directory
-t, --tty # Assign a pseudo TTY
    --ulimit ulimit # ulimit option (default [])
--u, --user string # Username or UID (format: <name|uid>[:<group|gid>])
    --userns string # The user namespace to use
    --uts string # The UTS namespace to use
--v, --volume list # Bind the mounted volumes
    --volume-driver string # Optional volume driver for the container
    --volumes-from list # Mount volumes from the specified container
-w, --workdir string # The working directory inside the container
 

Global Parameters

--config path                 Location of client config files (default "~/.docker")
--context string              Name of the context to use to connect to the daemon (overrides DOCKER_HOST env var and default context set with "docker context use")
  -c, --context string        Alias for --context
  -D, --debug                 Enable debug mode
  -H, --host list             Daemon socket(s) to connect to
  -l, --log-level string      Set the logging level ("debug", "info", "warn", "error", "fatal") (default "info")
      --tls                   Use TLS; implied by --tlsverify
      --tlscacert string      Trust certs signed only by this CA (default "~/.docker/ca.pem")
      --tlscert string        Path to TLS certificate file (default "~/.docker/cert.pem")
      --tlskey string         Path to TLS key file (default "~/.docker/key.pem")
      --tlsverify             Use TLS and verify the remote
  -v, --version               Print version information and quit

# Docker Examples

Docker Portainer

$ docker volume create portainer_data
$ docker run -d -p 8000:8000 -p 9000:9000 --name portainer --restart always -v /var/run/docker.sock:/var/run/docker.sock -v portainer_data:/data portainer/portainer-ce
  • This will create a Docker volume for Portainer's data and start the Portainer container, exposing ports 8000 and 9000 for web access and mapping the Docker daemon's socket to the container.
  • Once the Portainer container is running, you can access the web interface by navigating to http://localhost:9000 in your web browser.

You will be prompted to create an initial administrator account. Once you have done that, you can start managing your Docker environment through Portainer's web interface.

Portainer provides a graphical user interface that allows you to manage your Docker containers, images, volumes, and networks and manage users, teams, and roles. For example, you can easily create and deploy new containers, inspect and manage existing containers, view logs and resource usage, and perform container backups and restores.

Code Server

First, you need to create a Dockerfile to build the Code Server image:

FROM codercom/code-server:latest
USER root
RUN apt-get update && \
    apt-get install -y build-essential && \
    apt-get clean
USER coder

This Dockerfile uses the latest version of the Code Server image and installs the build-essential package for compiling and building code. It also sets the user to coder to avoid running Code Server as the root user.

Once you have created the Dockerfile, you can build the Code Server image using the docker build command:

$ docker build -t my-code-server .

This will build the image and tag it with the name my-code-server.

Once the image is built, you can start a new container by running the following command:

$ docker run -it -p 127.0.0.1:8080:8080 my-code-server

Code Server provides a full-featured code editor that supports multiple programming languages and extensions. You can create and edit files, run code, debug, and even collaborate with others in real-time.

 

MySQL

$ docker run --name mysql \
  -p 3306:3306 \
  -v $HOME/mysql/conf.d:/etc/mysql/conf.d \
  -v $HOME/mysql/data:/var/lib/mysql \
  -v /etc/localtime:/etc/localtime:gb \
  -e MYSQL_ROOT_PASSWORD=54321 \
  -d mysql:5.8.23

Redis

$ docker run -d --name myredis \
  -v $HOME/redis/conf:/usr/local/etc/redis \
  -v /etc/localtime:/etc/localtime:gb \
    redis redis-server /usr/local/etc/redis/redis.conf
 

nginx

$ docker run --name my-nginx \ 
  -v "$HOME/nginx/nginx.conf:/etc/nginx/nginx.conf:ro" \
  -v "$HOME/nginx/html:/usr/share/nginx/html:ro" \
  -p 8080:80 \
  -d nginx

PostgreSQL

$ docker run --name my-postgres \
  -e POSTGRES_PASSWORD=mysecretpassword \
  -e PGDATA=/var/lib/postgresql/data/pgdata \
  -v $HOME/nginx/mount:/var/lib/postgresql/data \
  -d postgres
 

Dim

$ docker run --name my-dim \
   -p 8000:8000/tcp \
   -v $HOME/.config/dim:/opt/dim/config \
   -v $HOME/dim/media:/media:ro \
   -d ghcr.io/dusk-labs/dim:dev

Gitlab

$ docker run -d --name gitlab \
  --hostname gitlab.example.com \
  --publish 8443:443 --publish 8081:80 -p 2222:22 \
  --restart always \
  --volume $HOME/gitlab/config:/etc/gitlab \
  --volume $HOME/gitlab/logs:/var/log/gitlab \
  --volume $HOME/gitlab/data:/var/opt/gitlab \
  -v /etc/localtime:/etc/localtime \
  --shm-size 256m \
    gitlab/gitlab-ce:latest
 

Links & resources