Docker Cheat Sheet & Reference
Docker Cheat Sheet & Reference
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
stats
docker ps list the running containers
docker ps -a list 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
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 images list all docker images
docker import [url] [new-image-name] create a new docker image from a remote file
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 network disconnect [network-name] [container-name] disconnect a container from a docker network
docker network create --driver overlay [network-name] create a docker swarm overlay network
docker network create --driver bridge --subnet [subnet]
create a bridge network with a specified subnet
[network-name]
docker network create --driver macvlan --subnet [subnet] -o create a mac vlan network with a specified subnet
parent=[interface-name] [network-name] and parent interface
create a network
Docker Hub
Docker Services
docker service create create a new docker service in a docker swarm cluster
docker service ls list all docker services running in a docker swarm cluster
display detailed information on a docker service running in a docker
docker service inspect
swarm cluster
docker service update update a docker service running in a docker swarm cluster
docker service rm remove a docker service running in a docker swarm cluster
scale the number of replicas in a docker service running in a docker
docker service scale
swarm cluster
docker service logs view the logs of a docker service running in a docker swarm cluster
docker service ps list the tasks in a docker service running in a docker swarm cluster
docker service create --network create a docker service in a specific network in a docker swarm cluster
create a docker service with a specified number of replicas in a docker
docker service create --replicas
swarm cluster
docker service create --mount mount a volume to a docker service running in a docker swarm cluster
set placement constraints for a docker service running in a docker swarm
docker service create --constraint
cluster
set environment variables for a docker service running in a docker swarm
docker service create --env
cluster
add metadata labels to a docker service running in a docker swarm
docker service create --label
cluster
set the update strategy for a docker service running in a docker swarm
docker service create --mode
cluster
docker service create --health-cmd set a health check command for a docker service running in a docker
swarm cluster
Docker Stack
docker stack deploy --compose-file deploy a docker stack using a compose file
docker stack deploy --with-registry-auth deploy a docker stack and authenticate with a private registry
docker stack deploy --prune remove any old services that are no longer part of the docker stack
docker stack deploy --resolve-image always always attempt to resolve the latest version of an image
docker stack deploy --orchestrator kubernetes deploy 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
create a virtual machine with the virtualbox driver named
docker-machine create --driver virtualbox myvm1
myvm1
docker-machine create -d hyperv --hyperv-virtual-switch create a virtual machine with the hyper-v driver named
"myswitch" myvm1 myvm1 using the myswitch virtual switch
display basic information about the myvm1 virtual
docker-machine env myvm1
machine
list the nodes in your cluster on the myvm1 virtual
docker-machine ssh myvm1 "docker node ls"
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
view the join token on the myvm1 virtual machine
worker"
open an ssh session with the myvm1 virtual machine; exit
docker-machine ssh myvm1
the session by typing "exit"
let workers leave the swarm on the myvm2 virtual
docker-machine ssh myvm2 "docker swarm leave"
machine
let the master leave and kill the swarm on the myvm1
docker-machine ssh myvm1 "docker swarm leave -f"
virtual machine
docker-machine start myvm1 start 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
copy the docker-compose.yml file to the home directory
docker-machine scp docker-compose.yml myvm1:~
of the myvm1 virtual machine
docker-machine ssh myvm1 "docker stack deploy -c <file> deploy an application on the myvm1 virtual machine
<app>" using the specified compose file and app name
Main Commands
attach attaches local standard input, output, and error streams to a running container
build builds images from dockerfile
commit creates a new image from container changes
cp copies files/folders between the container and the local filesystem
create creates a new container
diff checks for changes to files or directories on the container filesystem
events gets live events from the server
exec runs a command in the running container
export exports the container's filesystem to a tar archive
history shows the history of the image
images lists the images
import imports the contents from tarball to create a file system image
info displays system-wide information
inspect returns low-level information about docker objects
kill kills one or more running containers
load loads an image from a tar archive or stdin
login logs in to the docker registry
logout logs out from the docker registry
logs gets logs of containers
pause suspends all processes in one or more containers
port lists the container's port mappings or specific mappings
ps lists containers
pull pulls a mirror or repository from the registry
push pushes the image or repository to the registry
rename renames a container
restart restarts one or more containers
rm removes one or more containers
rmi removes one or more mirrors
run runs a command in a new container
save saves one or more images to a tar archive (streams to stdout by default)
search searches for images in docker hub
start starts one or more stopped containers
stats shows a live stream of container resource usage statistics
stop stops one or more running containers
tag creates a tag that references SOURCE_IMAGE TARGET_IMAGE
top displays the running processes of a container
unpause unpauses all processes in one or more containers
update updates the configuration of one or more containers
version displays docker version information
wait blocks 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
--context string Name of the context to use to connect to the daemon (overrides DOCKER_HOST env var and default context set with
-l, --log-level string Set the logging level ("debug", "info", "warn", "error", "fatal") (default "info")
• 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
Dockerfile
FROM
Usage:
FROM <image>
FROM <image>:<tag>
FROM <image>@<digest>
Information:
• FROM can appear multiple times within a single Dockerfile in order to create multiple images. Simply make a note of the last
image ID output by the commit before each new FROM command.
• The tag or digest values are optional. If you omit either of them, the builder assumes a latest by default. The builder
returns an error if it cannot match the tag value.
MAINTAINER
Usage:
MAINTAINER <name>
The MAINTAINER instruction allows you to set the Author field of the generated images.
RUN
Usage:
RUN <command> #(shell form, the command is run in a shell, which by default is
/bin/sh -c on Linux or cmd /S /C on Windows)
RUN ["<executable>", "<param1>", "<param2>"] #(exec form)
Information:
• The exec form makes it possible to avoid shell string munging, and to RUN commands using a base image that does not
contain the specified shell executable.
• The default shell for the shell form can be changed using the SHELL command.
• Normal shell processing does not occur when using the exec form. For example, RUN ["echo", "$HOME"] will not do variable
substitution on $HOME.
CMD
Usage:
CMD ["<executable>","<param1>","<param2>"] #(exec form, this is the preferred form)
CMD ["<param1>","<param2>"] #(as default parameters to ENTRYPOINT)
CMD <command> <param1> <param2> #(shell form)
Information:
• The main purpose of a CMD is to provide defaults for an executing container. These defaults can include an executable, or they
can omit the executable, in which case you must specify an ENTRYPOINT instruction as well.
• There can only be one CMD instruction in a Dockerfile. If you list more than one CMD then only the last CMD will take effect.
• If CMD is used to provide default arguments for the ENTRYPOINT instruction, both the CMD and ENTRYPOINT instructions should
be specified with the JSON array format.
• If the user specifies arguments to docker run then they will override the default specified in CMD.
• Normal shell processing does not occur when using the exec form. For example, CMD ["echo", "$HOME"] will not do variable
substitution on $HOME.
LABEL
Usage:
LABEL <key>=<value> [<key>=<value> …]
Information:
• To include spaces within a LABEL value, use quotes and backslashes as you would in command-line parsing.
• If Docker encounters a label/key that already exists, the new value overrides any previous labels with identical keys.
• To view an image’s labels, use the docker inspect command. They will be under the "Labels" JSON attribute.
EXPOSE
Usage:
EXPOSE <port> [<port> …]
Information:
• Informs Docker that the container listens on the specified network port(s) at runtime.
• EXPOSE does not make the ports of the container accessible to the host.
ENV
Usage:
ENV <key> <value>
ENV <key>=<value> [<key>=<value> …]
Information:
• The ENV instruction sets the environment variable <key> to the value <value>.
• The value will be in the environment of all “descendant” Dockerfile commands and can be replaced inline as well.
• The environment variables set using ENV will persist when a container is run from the resulting image.
• The first form will set a single variable to a value with the entire string after the first space being treated as the <value> -
including characters such as spaces and quotes.
ADD
Usage:
ADD <src> [<src> ...] <dest>
ADD ["<src>", ... "<dest>"] #(this form is required for paths containing whitespace)
Information:
• Copies new files, directories, or remote file URLs from <src> and adds them to the filesystem of the image at the path
<dest>.
• <src> may contain wildcards and matching will be done using Go’s filepath.Match rules.
• If <src> is a file or directory, then they must be relative to the source directory that is being built (the context of the build).
• If <dest> doesn’t exist, it is created along with all missing directories in its path.
COPY
Usage:
COPY <src> [<src> ...] <dest>
COPY ["<src>", ... "<dest>"] #(this form is required for paths containing whitespace)
Information:
• Copies new files or directories from <src> and adds them to the filesystem of the image at the path <dest>.
• <src> may contain wildcards and matching will be done using Go’s filepath.Match rules.
• <src> must be relative to the source directory that is being built (the context of the build).
• If <dest> doesn’t exist, it is created along with all missing directories in its path.
ENTRYPOINT
Usage:
ENTRYPOINT ["<executable>", "<param1>", "<param2>"] #(exec form, preferred)
ENTRYPOINT <command> <param1> <param2> #(shell form)
Information:
• Command line arguments to docker run <image> will be appended after all elements in an exec form ENTRYPOINT and will
override all elements specified using CMD.
• The shell form prevents any CMD or run command line arguments from being used, but the ENTRYPOINT will start via the shell.
This means the executable will not be PID 1 nor will it receive UNIX signals. Prepend exec to get around this drawback.
• Only the last ENTRYPOINT instruction in the Dockerfile will have an effect.
VOLUME
Usage:
VOLUME ["<path>", ...]
VOLUME <path> [<path> …]
Creates a mount point with the specified name and marks it as holding externally mounted volumes from native host or other
containers.
USER
Usage:
USER <username | UID>
The USER instruction sets the user name or UID to use when running the image and for any RUN, CMD and ENTRYPOINT instructions
that follow it in the Dockerfile.
WORKDIR
Usage:
WORKDIR </path/to/workdir>
Information:
• Sets the working directory for any RUN, CMD, ENTRYPOINT, COPY, and ADD instructions that follow it.
• It can be used multiple times in the one Dockerfile. If a relative path is provided, it will be relative to the path of the previous
WORKDIR instruction.
ARG
Usage:
ARG <name>[=<default value>]
Information:
• Defines a variable that users can pass at build-time to the builder with the docker build command using the --build-arg
<varname>=<value> flag.
• It is not recommended to use build-time variables for passing secrets like github keys, user credentials, etc. Build-time variable
values are visible to any user of the image with the docker history command.
• Environment variables defined using the ENV instruction always override an ARG instruction of the same name.
• Docker has a set of predefined ARG variables that you can use without a corresponding ARG instruction in the Dockerfile.
Information:
• Adds to the image a trigger instruction to be executed at a later time, when the image is used as the base for another build.
The trigger will be executed in the context of the downstream build, as if it had been inserted immediately after the FROM
instruction in the downstream Dockerfile.
• Triggers are inherited by the "child" build only. In other words, they are not inherited by "grand-children" builds.
• The ONBUILD instruction may not trigger FROM, MAINTAINER, or ONBUILD instructions.
STOPSIGNAL
Usage:
STOPSIGNAL <signal>
The STOPSIGNAL instruction sets the system call signal that will be sent to the container to exit. This signal can be a valid unsigned
number that matches a position in the kernel’s syscall table, for instance 9, or a signal name in the format SIGNAME, for instance
SIGKILL.
HEALTHCHECK
Usage:
HEALTHCHECK [<options>] CMD <command>
#(check container health by running a command inside the container)
HEALTHCHECK NONE #(disable any healthcheck inherited from the base image)
Information:
• Whenever a health check passes, it becomes healthy. After a certain number of consecutive failures, it becomes unhealthy.
◦ --retries=<number> (default: 3)
• The health check will first run interval seconds after the container is started, and then again interval seconds after each
previous check completes. If a single run of the check takes longer than timeout seconds then the check is considered to have
failed. It takes retries consecutive failures of the health check for the container to be considered unhealthy.
• There can only be one HEALTHCHECK instruction in a Dockerfile. If you list more than one then only the last HEALTHCHECK will
take effect.
• The command's exit status indicates the health status of the container.
• The first 4096 bytes of stdout and stderr from the <command> are stored and can be queried with docker inspect.
• When the health status of a container changes, a health_status event is generated with the new status.
SHELL
Usage:
SHELL ["<executable>", "<param1>", "<param2>"]
Information:
• Allows the default shell used for the shell form of commands to be overridden.
• Each SHELL instruction overrides all previous SHELL instructions, and affects all subsequent instructions.
• Allows an alternate shell be used such as zsh, csh, tcsh, powershell, and others.
docker-compose
Basic example
# docker-compose.yml
version: '2'
services:
web:
build: # build from Dockerfile
context: ./Path
dockerfile: Dockerfile
ports:
- "5000:5000"
volumes:
- .:/code
redis:
image: redis
Building
web:
# build from Dockerfile
build: .
args: # Add build arguments
APP_HOME: app
build: # build from custom Dockerfile
context: ./dir
dockerfile: Dockerfile.dev
# build from image
image: ubuntu
image: ubuntu:14.04
image: tutum/influxdb
image: example-registry:4000/postgresql
image: a4bc65fd
Ports
ports:
- "3000"
- "8000:80" # host:container
# expose ports to linked services (not to host)
expose: ["3000"]
Commands
# command to execute
command: bundle exec thin -p 3000
command: [bundle, exec, thin, -p, 3000]
Environment variables
# environment vars
environment:
RACK_ENV: development
environment:
- RACK_ENV=development
volumes:
- /var/lib/mysql
- ./_data:/var/lib/mysql
# automatically restart container
restart: unless-stopped
# always, on-failure, no (default)
Advanced features
Labels
services:
web:
labels:
com.example.description: "Accounting web app"
DNS servers
services:
web:
dns: 8.8.8.8
dns:
- 8.8.8.8
- 8.8.4.4
Devices
services:
web:
devices:
- "/dev/ttyUSB0:/dev/ttyUSB0"
Healthcheck
# declare service healthy when `test` command succeed
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost"]
interval: 1m30s
timeout: 10s
retries: 3
start_period: 40s
Hosts
services:
web:
extra_hosts:
- "somehost:192.168.1.100"
External links
services:
web:
external_links:
- redis_1
- project_db_1:mysql
Volume
# mount host paths or named volumes, specified as sub-options to a service
db:
image: postgres:latest
volumes:
- "/var/run/postgres/postgres.sock:/var/run/postgres/postgres.sock"
- "dbdata:/var/lib/postgresql/data"
volumes:
dbdata:
Network
# creates a custom network called `frontend`
networks:
frontend:
External network
# join a pre-existing network
networks:
default:
external:
name: frontend
User
# specifying user
user: root