Contents

Docker Commands Cheat Sheet

A cheat-sheet reference for Docker-related commands, focused on the Docker CLI and Compose CLI.

Copyright notice: This is an original article by xwi88, licensed under CC BY-NC 4.0. Commercial use is prohibited; please cite the source when reposting. Follow at https://github.com/xwi88

  • Docker version: Docker version 20.10.12, build e91ed57
  • Compose version: Docker Compose version 2.2.2

Docker reference resources

File formats

File formatDescription
DockerfileDefines the contents and startup behavior of a single container
Compose fileDefines a multi-container application

Command-line interfaces (CLIs)

CLIDescription
Docker CLIThe main CLI for Docker, includes all docker commands
Compose CLIThe CLI, which allows you to build and run multi-container applications
dockerdPersistent process that manages containers

Application programming interfaces (APIs)

APIDescription
Engine APIThe main API for Docker, provides programmatic access to a daemon
Registry APIFacilitates distribution of images to the engine
Docker Hub APIAPI to interact with Docker Hub

Drivers & specs

DriverDescription
Image specificationDescribes the various components of a Docker image
Registry token authenticationOutlines the Docker registry authentication scheme
Registry storage driversEnables support for given cloud providers when storing images with Registry

Docker CLI usage

Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
Usage:  docker [OPTIONS] COMMAND

A self-sufficient runtime for containers

Options:
      --config string      Location of client config files (default "/Users/wangxin/.docker")
  -c, --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")
  -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 "/Users/wangxin/.docker/ca.pem")
      --tlscert string     Path to TLS certificate file (default "/Users/wangxin/.docker/cert.pem")
      --tlskey string      Path to TLS key file (default "/Users/wangxin/.docker/key.pem")
      --tlsverify          Use TLS and verify the remote
  -v, --version            Print version information and quit

Management Commands:
  builder     Manage builds
  buildx*     Docker Buildx (Docker Inc., v0.7.1)
  compose*    Docker Compose (Docker Inc., 2.2.2)
  config      Manage Docker configs
  container   Manage containers
  context     Manage contexts
  image       Manage images
  manifest    Manage Docker image manifests and manifest lists
  network     Manage networks
  node        Manage Swarm nodes
  plugin      Manage plugins
  scan*       Docker Scan (Docker Inc., v0.17.0)
  secret      Manage Docker secrets
  service     Manage services
  stack       Manage Docker stacks
  swarm       Manage Swarm
  system      Manage Docker
  trust       Manage trust on Docker images
  volume      Manage volumes

Commands:
  attach      Attach local standard input, output, and error streams to a running container
  build       Build an image from a Dockerfile
  commit      Create a new image from a container's changes
  cp          Copy files/folders between a container and the local filesystem
  create      Create a new container
  diff        Inspect changes to files or directories on a container's filesystem
  events      Get real time events from the server
  exec        Run a command in a running container
  export      Export a container's filesystem as a tar archive
  history     Show the history of an image
  images      List images
  import      Import the contents from a tarball to create a filesystem image
  info        Display system-wide information
  inspect     Return low-level information on Docker objects
  kill        Kill one or more running containers
  load        Load an image from a tar archive or STDIN
  login       Log in to a Docker registry
  logout      Log out from a Docker registry
  logs        Fetch the logs of a container
  pause       Pause all processes within one or more containers
  port        List port mappings or a specific mapping for the container
  ps          List containers
  pull        Pull an image or a repository from a registry
  push        Push an image or a repository to a registry
  rename      Rename a container
  restart     Restart one or more containers
  rm          Remove one or more containers
  rmi         Remove one or more images
  run         Run a command in a new container
  save        Save one or more images to a tar archive (streamed to STDOUT by default)
  search      Search the Docker Hub for images
  start       Start one or more stopped containers
  stats       Display a live stream of container(s) resource usage statistics
  stop        Stop one or more running containers
  tag         Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE
  top         Display the running processes of a container
  unpause     Unpause all processes within one or more containers
  update      Update configuration of one or more containers
  version     Show the Docker version information
  wait        Block until one or more containers stop, then print their exit codes

Run 'docker COMMAND --help' for more information on a command.

To get more help with docker, check out our guides at https://docs.docker.com/go/guides/

Docker Compose CLI usage

Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
Usage:  docker compose [OPTIONS] COMMAND

Docker Compose

Options:
      --ansi string                Control when to print ANSI control characters ("never"|"always"|"auto") (default "auto")
      --compatibility              Run compose in backward compatibility mode
      --env-file string            Specify an alternate environment file.
  -f, --file stringArray           Compose configuration files
      --profile stringArray        Specify a profile to enable
      --project-directory string   Specify an alternate working directory
                                   (default: the path of the Compose file)
  -p, --project-name string        Project name

Commands:
  build       Build or rebuild services
  convert     Converts the compose file to platform's canonical format
  cp          Copy files/folders between a service container and the local filesystem
  create      Creates containers for a service.
  down        Stop and remove containers, networks
  events      Receive real time events from containers.
  exec        Execute a command in a running container.
  images      List images used by the created containers
  kill        Force stop service containers.
  logs        View output from containers
  ls          List running compose projects
  pause       Pause services
  port        Print the public port for a port binding.
  ps          List containers
  pull        Pull service images
  push        Push service images
  restart     Restart containers
  rm          Removes stopped service containers
  run         Run a one-off command on a service.
  start       Start services
  stop        Stop services
  top         Display the running processes
  unpause     Unpause services
  up          Create and start containers
  version     Show the Docker Compose version information

Run 'docker compose COMMAND --help' for more information on a command.

Docker commands

Common management commands

  • docker context [--help] context management
  • docker compose [--help] docker compose commands v2.2.2+
  • docker container [--help] container commands
  • docker image [--help] image commands
    • docker image prune remove untagged (<none>) images and images not used by any container
  • docker volume [--help] volume (directory mount) commands
  • docker network [--help] network commands
  • docker system [--help] system commands
    • docker system df show disk usage
    • docker system info == docker info Display system-wide information
  • docker scan [--help] scan and analyze images
  • docker manifest [--help] view image manifests; experimental

Common commands

  • docker build [--help] build an image
    • docker build [[-t tag] ...] -f [PATH/Dockerfile] .
    • docker build -t tag1 -t tag2 -f [PATH/Dockerfile] . build multiple tags at once
  • docker commit [OPTIONS] <container> <REPOSITORY[:TAG]> create an image from a container
  • docker cp copy files between a container and the local filesystem
    • docker cp [OPTIONS] CONTAINER:SRC_PATH DEST_PATH|-
    • docker cp [OPTIONS] SRC_PATH|- CONTAINER:DEST_PATH
  • docker create [OPTIONS] IMAGE [COMMAND] [ARG...] — usually you just use docker run to create and run
  • docker history = docker image history view image history
  • docker images list images
  • docker login
  • docker search
  • docker tag
  • docker pull
  • docker build
  • docker run
  • docker push
  • docker stop
  • docker logs

docker image filtering

docker images -f [filter params]

  • dangling=(true|false) none-tag images
  • label=<key> or label=<key>=<value> filter by label
  • before=(<image-name>[:tag]|<image-id>|<image@digest>)
  • since=(<image-name>[:tag]|<image-id>|<image@digest>)
  • reference=(pattern of an image reference)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
docker images -f dangling=true
docker images -f label=author
docker images -f label=author=xwi88
docker images -f reference="v8fg/*"
docker images -f reference="v8fg/alpine"
docker images -f reference="v8fg/alpine:*"
docker images -f reference="v8fg/golang:1.18*"
docker images -f reference="v8fg/golang:*1.18*"
docker images -f reference="[REPOSITORY:TAG]"
docker images -f reference="tes*"
docker images -f reference="test"
docker images -f reference="test*2"
Warning
In testing, if REPOSITORY contains /, the reference regex must include / to match — the filter regex does not match /.

docker commit — create an image from a container

docker commit [OPTIONS] CONTAINER [REPOSITORY[:TAG]]

1
2
3
4
5
6
7
8
9
Usage:  docker commit [OPTIONS] CONTAINER [REPOSITORY[:TAG]]

Create a new image from a container's changes

Options:
  -a, --author string    Author (e.g., "John Hannibal Smith <hannibal@a-team.com>")
  -c, --change list      Apply Dockerfile instruction to the created image
  -m, --message string   Commit message
  -p, --pause            Pause container during commit (default true)

prune — one-shot cleanup of images, containers, etc.

  • docker image prune -a remove all images not used by any container
  • docker container prune remove all stopped containers
  • docker volume prune remove all unmounted volumes
  • docker system prune remove all docker resources
  • docker network prune remove all networks

Simple Cheat Sheet

  • demo images: v8fg/demo
  • demo image: v8fg/demo[:latest]
  • demo container name: v8fg-demo

Running Containers

commandnote
docker run -it v8fg/demo bashRun container and specify command
docker run -it v8fg/demoRun container
docker run -tid v8fg/demoRun container detatched, -tty
docker create -ti v8fg/demoCreate a container without starting it
docker run -tid --name v8fg-demo v8fg/demonamed container
docker psshow running containers
docker ps -ashow all containers
docker ps --filter name=v8fgshow matching containers
docker ps --filter name=demo -qshow matching container ID
docker inspect v8fg-demoinspect container
Example

After the above, partial output:

1
2
3
4
5
6
CONTAINER ID   IMAGE       COMMAND     CREATED              STATUS                          PORTS     NAMES
01430cc7b2c0   v8fg/demo   "/bin/sh"   11 seconds ago       Up 11 seconds                             v8fg-demo
83ce7dee0346   v8fg/demo   "/bin/sh"   About a minute ago   Created                                   thirsty_bassi
1bd61cc802f1   v8fg/demo   "/bin/sh"   About a minute ago   Up About a minute                         relaxed_beaver
be104825d061   v8fg/demo   "/bin/sh"   About a minute ago   Exited (0) About a minute ago             flamboyant_beaver
8cfe1c19773f   v8fg/demo   "bash"      About a minute ago   Exited (0) About a minute ago             flamboyant_euclid

Container Lifecycle Stuff

commandnote
docker start v8fg-demostart
docker stop v8fg-demostop
docker stop v8fg-demo relaxed_beaverstop mutliple
docker restart v8fg-demorestart container
docker pause v8fg-demopauses a running container, freeze in place
docker unpause v8fg-demounpause a container
docker wait v8fg-demoblocks until running container stops
docker kill v8fg-demosends SIGKILL, faster than stop
docker rm v8fg-demoremove
docker rm v8fg-demo relaxed_beaverremove multiple
docker rm -f v8fg-demoforce remove
docker container rm -f $(docker ps -aq)Remove all containers, running or stopped

Resource Limits and Controls

commandnote
docker run -tid -c 512 v8fg/demo50% cpu
docker run -tid --cpu-shares 2 v8fg/demoCPU shares (relative weight)
docker run -tid --cpus 2 v8fg/demonumber of CPUs
docker run -tid --cpuset-cpus=0,4,6 v8fg/demouse these cpus
docker run -tid -m 300M v8fg/demolimit memory
docker create -ti --storage-opt size=5G v8fg/demolimit storage, not on aufs
docker run -tid -m 300M --cpus 1 --name v8fg-demo v8fg/demolimit memory

Stats, Logs, and Events

commandnote
docker statsresourse stats for all containers
docker stats v8fg-demoresource stats for one container
docker top v8fg-demoshows processes in a container
docker logs v8fg-democontainer logs
docker eventswatch events in real time
docker port v8fg-demoshows public facing port of container
docker diff v8fg-demoshow changes to a container’s file system

Docker Images

commandnote
docker imagesshow images
docker history v8fg/demoshow history of image
docker image rm v8fg/demoremove image
docker image remove ddd4b27c1c67remove by id
docker image remove v8fg/demoremove image
docker rmi v8fg/demoremove image
docker rmi $(docker images -q)remove all images
Commit container to an image:
docker commit v8fg-demono repo name
docker commit v8fg-demo test1repo name
docker commit v8fg-demo v8fg/test1repo name
docker commit v8fg-demo v8fg/test1:my-updatetagged
docker commit v8fg-demo v8fg/test1:v1.2.3tagged

Export/Import/Save/Load

  • export, import: drops layer history; smaller — for base images, stripping history
  • save, load: keeps layer history; larger
commandnote
docker exportexport container to tarball archive stream
docker importcreate image from tarball, excludes history ( smaller image )
docker savesave image to tar archive stream ( includes parent layers )
docker loadload an image from tarball, includes history ( larger image )
Examples:
docker export v8fg-demo | gzip > v8fg-demo-container-export.tar.gz
cat v8fg-demo-container-export.tar.gz | docker import - v8fg-demo:latest-import
docker save v8fg/demo | gzip > v8fg-demo-image-save.tar.gz
docker load < v8fg-demo-image-save.tar.gz

Docker Hub/Registry

commandnote
docker loginLogin to Registry
docker logoutLogout of Registry
docker tag ddd4b27c1c67 v8fg/demo:local-v1Tag an image
docker push v8fg/demoPush to registry
docker search v8fg
docker search v8fg/golang
docker search golang
docker pull v8fg/demoPull it down, default latest
docker run v8fg/demo:alpineWill be downloaded if it isn`t here

Building Docker Images From A Dockerfile

commandnote
mkdir mydockerbuildCreate build dir
cd mydockerbuildcd into build dir
vi DockerfileEdit build instructions
docker build -t mydockerimage .
docker imagesShow images
docker run mydockerimageRun the new image

Simple Dockerfile Example

v8fg/demo:latest

1
2
3
4
5
ARG FROM_REPOSITORY=alpine FROM_TAG=3.15.1
FROM ${FROM_REPOSITORY}:${FROM_TAG}
LABEL author=xwi88 type=demo name=latest github="https://github.com/xwi88" group="https://github.com/v8fg"
RUN apk add --no-cache tzdata bash
ENV TZ=Asia/Shanghai

v8fg/demo:ubuntu

1
2
3
4
FROM ubuntu
LABEL author=xwi88 type=demo name=ubuntu github="https://github.com/xwi88" group="https://github.com/v8fg"
RUN apt-get update && apt-get install nginx -y && apt-get clean && apt-get autoclean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
CMD ["/usr/sbin/nginx"]

Big Dockerfile Example

commandnote
FROM ubuntubase image
RUN apt updaterun commands while building
RUN apt install nginx -yrun commands while building
WORKDIR ~/working dir that CMD is run from
ENTRYPOINT echodefault application
CMD “echo” “Hello docker!”main command / default application
CMD ["--port 27017"]params for ENTRYPOINT
CMD “Hello docker!”params for ENTRYPOINT
ENV SERVER_WORKS 4set env variable
EXPOSE 8080expose a port, not published to the host
MAINTAINER authors_namedeprecated
LABEL version=“1.0”add metadata
LABEL author=“User One”add metadata
USER 751UID (or username) to run as
VOLUME ["/my_files"]sets up a volume
COPY test relativeDir/copies “test” to WORKDIR/relativeDir/
COPY test /absoluteDir/copies “test” to /absoluteDir/
COPY ssh_config /etc/ssh/ssh_configcopy over a vile
COPY --chown=user1:group1 files* /data/also changes ownership
ADD /dir1 /dir2like copy but does more …

Volumes/Storage

commandnote
docker info | grep -i storagecheck storage driver
docker inspect v8fg-demolook for “Mounts”
docker volume lsshow voluems
docker volume create testvol1create a volume
docker volume inspect testvol1inspect a volume
docker volume ls -f dangling=truefind dangling ( unused ) volumes
docker volume rm volume1remove volume
Running containers with volumes:
docker run -d --name test1 -v /data v8fg/demounamed volume mounted on /data
docker run -d --name test2 -v vol1:/data v8fg/demonamed volume
docker run -d --name test3 -v /src/data:/data v8fg/demobind mount
docker run -d --name test4 -v /src/data:/data:ro v8fg/demoRO
docker run -d --volumes-from test2 --name test5 v8fg/demostorage can be shared
docker rm -v test1remove container and unnamed volume
Access and sharing parameters:
:rofor read only
:zshared all containers can read/write
:Zprivate, unshared
-
`/var/lib/docker/overlay2`Defalt volume storage location on Ubuntu Linux

Expose Ports

commandnote
docker run -tid -p 1234:80 nginxexpose container port 80 on host port 1234
`docker run -tid -p 80:5000 ubuntu`bind port
docker run -tid -p 8000-9000:5000 ubuntubind port to range
`docker run -tid -p 80:5000/udp ubuntu`udp ports
`docker run -tid -p 127.0.0.1:80:5000 ubuntu`bind port on an interface
docker run -tid -p 127.0.0.1::5000 ubuntubind any port, specific interface
docker run -tid -P ubuntuexposed ports to random ports

Networks

commandnote
docker network lsshow networks, bridge is default
docker network inspect bridgeshow network details and connected containers
Create Bridge Network, Specify Subnet and Gateway:
docker network create -d bridge my-network
docker network create -d bridge --subnet 172.25.0.0/16 my-network
docker network create --subnet 203.0.113.0/24 --gateway 203.0.113.254 my-network
docker network rm my-networkremove network
Run container and specify network:
docker run -tid --net=my-network --name test1 ubuntu
Run container, specify network and IP:
docker run -tid --net=my-network --ip=172.25.3.3 --name=test1 ubuntu
Connect container to network:
docker network connect net1 test1
docker network connect net1 test2 --ip 172.25.0.102
Disconnect container from network:
`docker network disconnect net1 test1`Disconnect container from this network
docker network disconnect -f test1 test2Force disconnect
Find container’s IP address:
docker inspect -f '{{json .NetworkSettings.Networks}}' container1
docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' container1

References