Show Menu
Cheatography

Docker & Swarm 2022 Cheat Sheet by

Common commands used with Docker Desktop

General Commands

docker version
docker version --format '{{.Server.Version}}'
Get the server version
docker version --format '{{json .}}'
Dump raw JSON data
docker info -D
All docker commands to output debug info

docker container COMMAND

ls [OPTIONS]
list running containers
ls --all|-a
list all containers
ls --size|-s
list running containers sizes
ls -q
display container IDs of running container (q stands for quiet)
ls --format '{{printf "­%-4­0s" .Names}} {{.Ports}}'
display name and ports of running containers
start|­sto­p|p­aus­e|u­npa­use­|re­sta­rt|rm CONTAINER
start, stop, pause, unpause, restart or remove container
logs --tail|-n 10 CONTAINER
show the last 10 lines of logs
logs [OPTIONS] CONTAINER
fetch the logs of a container
logs --time­sta­mps|-t CONTAINER
show logs including timestamps
run [OPTIONS] IMAGE [COMMAND] [ARG...]
create a new container and run a command into it
run --name CONTAINER nginx:­1.22.0
create CONTAINER using nginx image tagged 1.22.0
run -p 8080:80 IMAGE
maps the host port 8080 to the created container port 80
run --deta­ch|-d IMAGE
run container in background and print container ID
run --rm -it IMAGE CMD
create a container, run a cmd on it intera­cti­vely, then delete the container
run --net NETWORK IMAGE
--net connects a container to NETWORK
run -d --name mysql -e MYSQL_­ALL­OW_­EMP­TY_­PAS­SWO­RD=True -v mysql-­db:­/va­r/l­ib/­mysql mysql
create a named volume mysql-db pointing to the container directory /var/l­ib/­mysql
run -d --name nginx -p 80:80 -v $(pwd)­:/u­sr/­sha­re/­ngi­nx/html nginx
create a bind mount between the host current directory and /usr/s­har­e/n­gin­x/html
run --name postgr­es-db -e POSTGR­ES_­PAS­SWO­RD=­pas­sword --mount type=v­olu­me,­sou­rce­=$H­OME­/do­cke­r/v­olu­mes­/po­stg­res­,ta­rge­t=/­var­/li­b/p­ost­gre­sql­/data -p 2000:5432 -d postgres
create a named volume between the host directory $HOME/­doc­ker­/vo­lum­es/­pos­tgres and the container directory /var/l­ib/­pos­tgr­esq­l/data
run --name postgr­es-db -e POSTGR­ES_­PAS­SWO­RD=­pas­sword --v $HOME/­doc­ker­/vo­lum­es/­pos­tgr­es:­/va­r/l­ib/­pos­tgr­esq­l/data -p 2000:5432 -d postgres
create a named volume between the host directory $HOME/­doc­ker­/vo­lum­es/­pos­tgres and the container directory /var/l­ib/­pos­tgr­esq­l/data
run -d --name postgr­es-db -e POSTGR­ES_­PAS­SWO­RD=­pas­sword --mount type=b­ind­,so­urc­e="$­pwd­"­,ta­rge­t=/­var­/li­b/p­ost­gre­sql­/data -p 2000:5432 -d postgres
create a bind mount between the host current directory and the /var/l­ib/­pos­tgr­esql/ directory in the container.
run --heal­th-­cmd­="curl -f localh­ost­:92­00/­_cl­ust­er/­health || false" --heal­th-­int­erv­al=5s --heal­th-­ret­ries=3 --heal­th-­tim­eout=2s --heal­th-­sta­rt-­per­iod=15s IMAGE
health check
ps -a --filter volume­=VOLUME
display all containers using VOLUME
ps --no-trunc
prevent truncating output
 
top CONTAINER [ps OPTIONS]
display the running processes of a container
 
rm --force|-f CONTAINER
force the removal of a running container (uses SIGKILL)
stats [OPTIONS] CONTAINER
display a live stream of running contai­ner(s) resource usage statistics
stats --all|-a CONTAINER
display a live stream of ALL running contai­ner(s) resource usage statistics
inspect --size|-s --pretty CONTAINER
display detailed inform­ation on one or more containers with size
update -c 4 -m 8G CONTAINER
commit [OPTIONS] CONTAINER [REPOS­ITO­RY[­:TAG]]
Create a new image from a contai­ner’s changes excepts on volumes.
commit --change "ENV DEBUG=­tru­e" CONTAINER [REPOS­ITO­RY[­:TAG]]
Apply Dockerfile instru­ction to the created image
exec -it CONTAINER sh -c "test -d /some/dir && echo 'It Exists­'"
test if a folder exists in a container
docker container inspect CONTAINER --format '{{json .Netwo­rkS­ett­ings}}' | jq
pretty print contai­ner's network info

docker image COMMAND

ls
List images. same as
docker images
inspect -f|--format='{{.Config.Cmd}}' IMAGE
Check available command (ex: sh or bash) available on the image
pull nginx
Pull the "­lat­est­" nginx image from dockerhub (default repo)
pull nginx:­1.11.9
Pull image nginx 1.11.9 from dockerhub
history [OPTIONS] IMAGE
Show the history of the IMAGE (layers)
tag SOURCE­_IM­AGE­[:TAG] TARGET­_IM­AGE­[:TAG]
Create a tag
push [OPTIONS] NAME[:TAG]
Push the USER/I­MAG­E:TAG image to DockerHub (default registry)
build [OPTIONS] PATH | URL | -
Build an image from a Docker­file. see options here
build --tag|-t IMAGE .
Build an image searching for a dockerfile in the host current directory and tag it
my_cus­t_image
build --target builder -t IMAGE:­latest .
Build from Dockerfile but stops at buil stage "­bui­lde­r" in a multi-­stage build docker­file.

docker volume

A volume gives full control of the storage** from the container. A new directory is created within Docker's storage directory on the host machine, and Docker manages that direct­ory's conten
Bind mounts gives full control of the storage from the host and contai­ners. It's not a secure option. A file or directory on the host machine is mounted into a container. The file or directory is referenced by its full or relative path on the host machine
ls
list volumes
inspect VOLUME
display detailed inform­ation on a volume
create --name VOLUME
create a volume
rm -f VOLUME
Remove a volume. -f to force
prune -f
Remove all unused local volumes. -f to force
docker container run --rm --volu­mes­-from CONTAINER -v $(pwd)­:/b­ackup ubuntu tar cvf /backu­p/b­ack­up.tar /NAMED_VOL
backup data from a container

docker network

ls
list all the networks
create <ne­two­rk>
create the <ne­two­rk> network
inspect -v <ne­two­rk> --pretty
display detailed inform­ation on a networks. -v for verbose
connect <ne­two­rk> <co­nta­ine­r>
connect a running container to a network
rm <ne­two­rk>
remove a network
prune
remove all unused networks
a bridge network is an isolated network on a single engine install (=single host)
create -d|--d­river bridge NET
an overlay network is an isolated network on a swarm (=across host)
create -d|--d­river overlay NET
create an overlay network used to enable commun­ication between containers more info here
All swarm service management traffic is encrypted by default, using the AES algorithm in GCM mode. Manager nodes in the swarm rotate the key used to encrypt gossip data every 12 hours.
create --opt encrypted NET
encrypt applic­ation data. enables IPSEC encryption at the level of the vxlan.
create --driver overlay --atta­chable NET
create an overlay network which can be used by swarm services or standalone containers
create =d|--d­river bridge NET
containers across the host

docker images

docker images
List the most recently created images
docker images -f 'dangl­ing­=true' -q
display untagged images that are the leaves of the images tree (not interm­ediary layers). These images occur when a new build of an image takes the repo:tag away from the image ID, leaving it as <no­ne>­:<n­one> or untagged. A warning will be issued if trying to remove an image when a container is presently using it. By having this flag it allows for batch cleanup.
docker rmi $(docker images -f "­dan­gli­ng=­tru­e" -q)
Clean up untagged images that are the leaves of the images tree (not interm­ediary layers). These images occur when a new build of an image takes the repo:tag away from the image ID, leaving it as <no­ne>­:<n­one> or untagged. A warning will be issued if trying to remove an image when a container is presently using it.

docker compose

Compose can only create services locally
A Service is a set of replicated containers
docker­-co­mpo­se.yaml
is the default file used but we can use the -f option to use another filename
up [OPTIONS] [SERVI­CE...]
Builds, (re)cr­eates, and then starts a set of defined services.
docker compose up builds the image from the dockerfile in the build section of the compose file only if not found in cache
-f docker­-co­mpo­se.yaml -f docker­-co­mpo­se.t­es­t.yaml up
Build test contai­ner(s) for services using
docker­-co­mpo­se.yaml
as base config overridden by
docker­-co­mpo­se.t­es­t.yaml
-f docker­-co­mpo­se.yml -f docker­-co­mpo­se.p­ro­d.yml config > output.yml up
Build prod contai­ner(s) and creates the a merged yaml file
up --build
rebuild the images even if found in cache
up -d|--d­etach
Create contai­ner(s) for service(s) in the backgr­ound.
up -p PROJEC­T_NAME
set a project name that will be the containers names prefix instead of the parent directory of the
compose file
down [OPTIONS]
Stops and removes contai­ners, networks, volumes, and images created by up.
down --rmi local|all
removes images of the service as well as contai­ners. Remove images used by services. "­loc­al" remove only images that don't have a custom tag
start|­sto­p|p­aus­e|u­npa­use­|re­sta­rt|kill [SERVI­CE...]
Start, stop, pause, unpause, restart, kill q service(s) and its contai­ner(s)
logs [OPTIONS] [SERVI­CE...]
Displays log output from containers of a service
ps [OPTIONS] [SERVI­CE...]
List containers of a service
top [SERVI­CE...]
Display the running processes of a service
build [OPTIONS] [SERVI­CE...]
Build or rebuild images but don't start the container
-f FILE build [OPTIONS] [SERVI­CE...]
Build or rebuild images specifying a Dockerfile
VAR=VALUE docker­-co­mpose build
pass variables at build time to compose
VAR=VALUE docker­-co­mpose up
pass variables at run time to compose
build --buil­d-arg GIT_PE­RSO­NAL­_AC­CES­S_T­OKE­N="{­TOK­EN}­"
Pass variables into Dockerfile through Docker Compose during build

docker service (Swarm)

A service is a set of replicated containers
A single service can have multiple tasks and each one will launch a container
create --name mydb --replicas 3 redis:­7-b­ullseye
Create a mydb service using 3 redis:­7-b­ullseye nodes
create --name mydb --replicas 2 --env MYVAR=foo --env MYVAR2=bar redis:­3.0.6
Create a mydb service specifying 2 env variables
create --name redis --secret source­=ss­h-k­ey,­tar­get=ssh --secret source­=ap­p-k­ey,­tar­get­=ap­p,u­id=­100­0,g­id=­100­1,m­ode­=0400 redis:­3.0.6
Creates /run/s­ecr­ets/ssh and /run/s­ecr­ets/app in the container
create --name frontend --network <ne­t> -p 8081:80 nginx
Creates a network attached to <ne­t>. exposes port 80 reachable throught the host port 8081
create --name db --network backend --mount type=v­olu­me,­sou­rce­=db­-da­ta,­tar­get­=/v­ar/­lib­/po­stg­res­ql/data -e POSTGR­ES_­HOS­T_A­UTH­_ME­THO­D=trust --replicas 1 postgr­es:9.4
Create a postgres "­db" service with a named volume, attached to the backend network
create --name SERVICE --network NET IMAGE
Creates a SERVICE and attach it to the existing NET network. The swarm extends NET to each node running the service.
create --name pgserv -e POSTGR­ES_­HOS­T_A­UTH­_ME­THO­D=trust --heal­th-­cmd­="pg­_is­ready -U postgres || exit 1" --heal­th-­sta­rt-­period 120s postgr­es:­latest
Creates a
pgserv
service with health checks executed every 30sec (default) but the failure counts begins after 120s
create --name SERVICE -p HOST_P­ORT­:CO­NTA­INE­R_PORT --replicas 5 --deta­ch=­false REGIST­RY_­HOS­T:R­EGI­STR­Y_H­OST­/IMAGE
Create a service from a custom registry
ls
List services running in the swarm
ps SERVICE
List the tasks of one or more services
inspect SERVICE
Display detailed inform­ation on one or more services
logs SERVICE
Batch-­ret­rieves logs present at the time of execution
rm SERVICE
Removes the specified services from the swarm.
update [OPTIONS] SERVICE
Update a service
update --replicas 10 --rese­rve-cpu 4 --rese­rve­-memory 16G SERVICE
Change cpu and ram and max tasks.
update --moun­t-add type=v­olu­me,­sou­rce­=ot­her­-vo­lum­e,t­arg­et=­/so­mew­her­e-else SERVICE
Add a named volume
other-­volume
pointing to
/somew­her­e-else
. note the syntax --opti­on-add & *--opt­ion-rm
update --mount-rm PATH myservice
Remove the PATH volume. a path always begins with a /
update --secr­et-add source­=ss­h-2­,ta­rge­t=ssh-2 --secr­et-rm ssh-1 myservice
Add/remove secret. note the syntax --opti­on-add & --opti­on-rm
update --rollback SERVICE
Rollback a service to its previous state
update --image IMAGE SERVICE
Change the image of a service
update --publ­ish-rm HOST_PORT --publ­ish-add HOST_P­ORT­:CO­NTA­INE­R_P­ORT> SERVICE
Replace a port in containers of a service
scale SERVIC­E=R­EPLICAS
Scale one or multiple replicated services. a replica is a task
update --force SERVICE
Force update of a service to rebalance the load across the swarm.

docker node (swarm)

ls
list nodes in the swarm
ps NODE
list the running task in a node or current node by default
promot­e|d­emote NODE [NODE...]
promote or demote a node to manager or worker
rm -f NODE [NODE...]
remove a node from a swarm. -f to force
inspect --pretty self|NODE [NODE...]
Display detailed and pretty­-pr­inted info on one or more nodes
inspect --format '{{ .Statu­s.Addr }}' self|NODE [NODE...]
get the node IP address
ls -f "­rol­e=m­ana­ger­" -f node.l­abe­l=r­egi­on=­reg­ion-a
list manager nodes having a region label set to region-a
update [OPTIONS] NODE
update a node
update --labe­l-add LABEL_­KEY­=LA­BEL­_VALUE NODE [LABEL­_KE­Y=L­ABE­L_VALUE NODE...]
update <no­de> adding a label key/value

docker stack (swarm)

stacks are compose for production swarms and accepts compose files but can't build images
deploy --comp­ose­-fi­le|-c docker­-co­mpo­se.yml --comp­ose­-fi­le|-c docker­-co­mpo­se.p­ro­d.yml STACK
Deploy or update the prod stack using the
docker­-co­mpo­se.yml
base config and the
docker­-co­mpo­se.p­ro­d.yml
for specific prod conf
cat <do­cke­r-c­omp­ose.ym­l> | docker stack deploy --comp­ose­-file - <st­ack>
Create or update a stack using the std input (
-
opt)
deploy -c <do­cke­r-c­omp­ose­-1.y­ml> -c <do­cke­r-c­omp­ose­-2.y­ml­><s­tac­k>
Deploy a stack using multiple compose files. It must be exec on a Manager node
ls [OPTIONS]
Lists the stacks.
ls --format "­table {{.Name}}: {{.Services}}"
Output stacks with the Name and Services
ps [OPTIONS] STACK
ps -f "­nam­e=r­edi­s.1­" -f "­nam­e=r­edi­s.7­" STACK
List the tasks that are part of the STACK named
redis.1
and
redis.7
ps -f "­nod­e=N­ODE­_01­" -f "­nod­e=N­ODE­_02­" STACK
List the tasks from NODE_01 and NODE_02
ps -f "­des­ire­d-s­tat­e=r­unn­ing­" -f "­des­ire­d-s­tat­e=r­ead­y"
List the tasks which desire­d-state is running or ready
ps --format "­table {{.Name}}: {{.Image}}, {{.CurrentState}}" STACK
Output tasks with the Name, Image and State
rm [OPTIONS] STACK [STACK...]
Removes one or more <st­ack>
services [OPTIONS] STACK
Lists the services that are running as part of the specified stack
services --filter name=web --filter name=db myapp
List both the web and db services

Secrets (swarm)

create [OPTIONS] SECRET [file|-]
Create a secret from a file or STDIN as content
create psql_user psql_u­ser.txt
Create the psql_user secret containing the value in psql_u­ser.txt
echo SECRET­_PASS | docker secret create psql_pass -
Create the secret psql_pass from stdin
ls [OPTIONS]
List secrets
ls --filter label=­project
List all secrets with a "­pro­jec­t" label
inspect SECRET
List info about SECRET
 
docker service create --name SERVICE --secret SECRET­_USER --secret SECRET­_PASS -e POSTGR­ES_­PAS­SWO­RD_­FIL­E=/­run­/se­cre­ts/­SEC­RET­_PASS -e POSTGR­ES_­USE­R_F­ILE­=/r­un/­sec­ret­s/S­ECR­ET_USER postgres
Use secrets inside the containers of a service
A secret can be a username, a password, a key or whatever shouldn't be seen from the outside.

Docker Registry

docker container run -d -p 5000:5000 --rest­art­=always -v $(pwd)­/re­gis­try­-da­ta:­/va­r/l­ib/­reg­istry --name registry registry:2
start the registry contai­ner.A produc­tio­n-ready registry must be protected by TLS and should ideally use an access­-co­ntrol mechanism.
docker run -d -p 5000:5000 --name <re­gis­try> --restart unless­-st­opped -v $(pwd)­/re­gis­try­-da­ta:­/va­r/l­ib/­reg­istry -v $(pwd)­/ce­rts­:/certs -e REGIST­RY_­HTT­P_T­LS_­CER­TIF­ICA­TE=­/ce­rts­/do­mai­n.crt -e REGIST­RY_­HTT­P_T­LS_­KEY­=/c­ert­s/d­oma­in.key registry
start a secured registry using host
./regi­str­y-data
data folder and
./certs/
for the signed cert and the private key
docker service create --name <re­gis­try> -p 5000:5000 registry
creates a registry in a swarm
 
docker login <RE­GIS­TRY­_HO­ST>­:<R­EGI­STR­Y_P­ORT>
1/2 Login to a private registry
docker service create --name SERVICE -p HOST_P­ORT­:CO­NTA­INE­R_PORT --replicas 5 --deta­ch=­false REGIST­RY_­HOS­T:R­EGI­STR­Y_H­OST­/IMAGE
2/2 Create a service from an image on a private registry
 
docker login <RE­GIS­TRY­_HO­ST>­:<R­EGI­STR­Y_P­ORT>
1/2 Login to a private registry
docker tag <IM­AGE­_ID> <RE­GIS­TRY­_HO­ST>­:<R­EGI­STR­Y_P­ORT­>/<­APP­NAM­E>:­<AP­PVE­RSI­ON>
2/2 Tag an image to a private registry
docker push <RE­GIS­TRY­_HO­ST>­:<R­EGI­STR­Y_P­ORT­>/<­IMA­GE>­:<T­AG>
3/3 Push an image to a private registry
           
 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

          Docker basics Cheat Sheet

          More Cheat Sheets by Boulard

          Photoshop 2021 Cheat Sheet
          Illustrator 2021 Cheat Sheet Cheat Sheet
          Multipass CLI 2022, Ubuntu VMs on demand on any OS Cheat Sheet