Uploaded by kmcexams

Docker Cheat Sheet: Commands & Examples

advertisement
1. sudo docker version //shows version info on client and server
2. sudo docker images //show images
sudo docker images --digests nginx
3. sudo docker pull ubuntu:images //pull images to docker host
sudo docker pull <repository>:<tag>
sudo docker pull nigelpoulton/tu-demo:v2 //unoffical registry, <user/org name/repo:tag>
sudo docker pull ghcr.io/regclient/regsync:latest // ghcr.io registry in place of docker hub
that implements OCI spec and Docker Registry c2 API
4. sudo docker info 2>&1 | less
//press ‘q’ to quit and back to command prompt
//shows details in client and server
5. docker run <arguments> <image> <command>
<command> is optional
sudo docker run
e.g
docker run --name {container_name} -it ubuntu:latest bash
docker run tells Docker to start a new container. The --name flag told Docker to call
this container test. Next, the -it flags told Docker to make the container interactive and
to attach your shell to the container’s terminal. After that, the command told Docker to
base the container on the ubuntu:latest image. Finally, it told Docker to start a Bash
shell as the container’s main app.
ps -elf inside container lists processes inside container
sudo docker run -d \
--name web1 \
--publish 8080:8080 \
test:latest
On windows replace ‘\’ with ‘~’(backtick)
docker run -d --name webserver -p 5005:8080 nigelpoulton/ddd-book:web0.1
docker run --rm -d alpine sleep 20
command starts a new background container based on the Alpine image and tells it to
run the sleep 20 command, causing it to run for 20 seconds and then exit. The --rm flag
cleans up the exited container so you don’t have to delete it manually.
flag
-d: starts the container in the background as a daemon process without occupying your
terminal window.
-p: maps port 5005 on your local system to port 8080 inside the container. This works
because the container’s web server is listening on port 8080.
docker port web//verify port mapping of “web” container. output shows the port mapping
exists on all interfaces on the Docker host
—dns : customized list of DNS servers
—dns-search: add custom search domain for queries against unqualified names
docker run -it --name custom-dns \
--dns=8.8.8.8 \
--dns-search=nigelpoulton.com \
alpine sh
The dns & dns-search info gets added to resolve.conf
cat /etc/resolv.conf
nameserver 8.8.8.8
search nigelpoulton.com
6. ctrl-pq //exit container without terminating it.
7. sudo docker ps //lists all running container.
8. sudo docker ps -a //lists also stopped container
sudo docker ps -l //list status of all container
9. sudo docker attach {container_name} // attach your shell to the Bash process inside
the container.
//ctrl-pq //exit container without terminating it.
10. sudo docker stop {container_name} //takes up to 10 sec to stop a container
gracefully
10.a. restart docker container sudo docker restart {container_name}
11. sudo docker rm {container_name} //kills a container
sudo docker rm {container_name} -f
Flag -f: forces the container to stop without allowing the buffer to flush and removes the
container, altogether.
docker ps -a //won’t show the container anymore. Any live changes are lost.
12. sudo docker build -t test:latest . //create new image test:latest
flag -t: tag
Period “.” tells Docker to use your current working directory as the build context. build
context is where application files and dependencies reside
docker build -t multi:client --target prod-client -f Dockerfile-final .
flag: -f : when default name of “Dockerfile” name is something else.
-target: tells the build which stage from “Dockerfile-final” to use
13. sudo docker rmi test:latest //delete image
14. docker inspect for image sudo docker inspect node:latest //get detailed image information
docker inspect nigelpoulton/ddd-book:web0.1 | grep Entrypoint -A 3
//command searches the image metadata and returns any lines containing the
word “Entrypoint” and the //three lines immediately following it.
15. sudo docker history node:latest //build history of an image I.e. see instructions that
created image
16. docker buildx imagetools inspect nigelpoulton/k8sbook:latest //obtain digest of i
mage from registry
17. docker pull nigelpoulton/k8sbook@sha256:13dd59a0...bce2 // pull image by digest
18. docker manifest inspect golang | grep 'architecture\|os' //shows architecture or os
from manifest list and associate manifests, command same as ‘buildx imagetools’
19. sudo docker rmi redis:latest af111729d35a sha256:c5b1261d...f8e1ad6b // deletes 3
images - by tag, short ID & she
20. docker rmi $(docker images -q) -f
// -q : flag that retrieves image ID.
// -f : flag for force delete.
21.
sudo groupadd docker
sudo usermod -aG docker <username> // to add user account as a member to the
docker Unix group
newgrp docker
sudo reboot
22.
docker exec -it webserver sh //interactive
docker exec webserver cat views/home.pug//remote execution
start an interactive exec session by creating a new shell process (sh) inside
the webserver container and connecting your terminal to it. The -it flag makes it
an interactive exec session, and the sh argument starts a new sh process inside the
container. sh is a minimal shell program installed in the container.
exit //exits out of the shell process
docker exec <container> <command>
docker exec webserver ps //executes and enlists all running processes inside the
container. Main process will always have PID as 1
23. docker inspect for container docker inspect {container_name}
24. Docker debug - paid subscription.
docker login //login to docker
docker info //shows in plugin section whether docker debug is installed.
Plugins:
debug: Get a shell into any image or container. (Docker Inc.)
Version: 0.0.29
Path:
/Users/nigelpoulton/.docker/cli-plugins/docker-debug
docker debug {container_name}
This is an attach shell, i.e.:
- Any changes to the container filesystem are visible to the container directly.
- The /nix directory is invisible to the actual container.
Opens a docker shell in the debugging container
docker> install bind package// if any tool not found then installing package from default
search.nixos.org would install the tool.
docker debug {image}
Note: This is a sandbox shell. All changes will not affect the actual image.
Version: 0.0.29 (BETA)
root@3f5b281b914b /src [nigelpoulton/ddd-book:web0.1]
docker >
25. Docker restart policy ·
·
·
·
no (default)
on-failure
always
unless-stopped
docker run --name neversaydie -it --restart always alpine sh
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED
STATUS
NAMES
1933623830bb alpine "sh"
15 seconds ago Up 2 seconds neversaydie
docker inspect neversaydie | grep RestartCount
"RestartCount": 1,
25.
If in Docker desktop, daemon is not running, then Docker is stopped, need to start
docker
docker init//run from project directory, analyses applications and automatically creates
Dockerfiles that implement good practices. Only available with docker desktop
26. docker tag ddd-book:ch8.node kaushikmcdocker/ddd-book:ch8.node//to tag same
image with another name. In this case to push to repository kaushikmcdocker/ddd-book
in docker hub
27. docker login//login to docker hub from terminal
28. docker push kaushikmcdocker/ddd-book:ch8.node//push to repository under user
kaushikmcdocker in docker hub
29. docker builds ls //lists the builders configured in the system
30. docker buildx create --driver=docker-container --name=container builder //create
new builder
docker buildx use container//make “container” builder as default
docker buildx build --builder=container --platform=linux/amd64,linux/arm64 -t
nigelpoulton/ddd-book:ch8.1 --push . //build images for AMD and ARM architectures.
Don’t have a Docker Hub account or don’t want to push the images, you can replace
the --push with --load.
Cloud builder docker buildx create --driver cloud nigelpoulton/ddd cloud-nigelpoulton-ddd
docker buildx build --builder=cloud-nigelpoulton-ddd --platform=linux/amd64,linux/arm64
-t nigelpoulton/ddd-book:ch8.1 --push .
32. docker compose version
33. docker compose up & //assume compose.yaml in current directory
docker compose up --detach
34. docker compose -f apps/ddd-book/sample-app.yml up &
hit Return to reclaim your shell prompt.
35. docker network ls //list networks
docker network inspect bridge//where bridge is a default network type based on
“docker0” in host’s kernel
docker network inspect bridge | grep bridge.name
"com.docker.network.bridge.name": "docker0",
brctl show //list all bridges in docker host
ip link show docker0 //shows state of docker0 bridge
docker network create -d bridge localnet// create new single-host bridge network called
“localnet”
docker network inspect localnet --format '{{json .Containers}}' | jq // verify the containers
information connected to localnet
36. docker volume ls //list volume
37. docker compose down //shutdown the app
38. docker compose ps //current state of app
39. docker compose top//lists processes inside each container
40. docker compose stop//stop an app
41. docker compose ls//lists all running Compose projects
42. docker-compose down --volumes --rmi all// —volumes delete volume and —rmi all
delete all images
Multipass
43. multipass launch docker --name mgr1 //create node with name mgr1
44 multipass ls //lists all nodes
45. multipass shell mgr1//logon to shell and execute command like check docker
version in it, type “exit” to return to local shell
46. docker swarm init//switches a node into swarm node
docker swarm init —external-ca //use external ca
47. Run from first manager(leader) to generate token for workers to join -
docker swarm join-token worker
To add a manager to this swarm, run the following command:
docker swarm join --token SWMTKN-1-0uahebax...c87tu8dx2c 192.168.64.61:2377
Rotate token docker swarm join-token --rotate manager
48. Run from first manager(leader) to generate token for managers to join -
docker swarm join-token manager
To add a manager to this swarm, run the following command:
docker swarm join --token SWMTKN-1-0uahebax...ue4hv6ps3p 192.168.64.61:2377
49.
docker swarm join \
--token SWMTKN-1-0uahebax...c87tu8dx2c \
10.0.0.1:2377 \
--advertise-addr 192.168.64.64:2377 \
--listen-addr 192.168.64.64:2377
This node joined a swarm as a worker.
47. Run from worker to join swarm.
docker swarm join \
--token SWMTKN-1-0uahebax...ue4hv6ps3p \
10.0.0.1:2377 \
--advertise-addr 192.168.64.62:2377 \
--listen-addr 192.168.64.62:2377
—advertise-addr: advertise node or external load balancer’s IP as swarm API endpoint
—listen-add: tells docker IP of the interface that accepts swarm traffic.
48. This node joined a swarm as a manager.
docker swarm join \
--token SWMTKN-1-0uahebax...ue4hv6ps3p \
10.0.0.1:2377 \
--advertise-addr 192.168.64.62:2377 \
--listen-addr 192.168.64.62:2377
49. Run the following command from one of your swarm managers to lock your existing
swarm cluster.
docker swarm update --autolock=true
Swarm updated.
To unlock a swarm manager after it restarts, run the `docker swarm unlock` command
and
provide the following key:
SWMKEY-1-XDeU3XC75Ku7rvGXixJ0V7evhDJGvIAvq0D8VuEAEaw
Please remember to store this key in a password manager...
50. Run on any manager to view your unlock key
docker swarm unlock-key
51. Restart Docker on one of your managers to see if it automatically re-joins the
cluster.
$ sudo systemctl restart docker
52. list the nodes in the swarm.
$ docker node ls
52. to unlock the swarm for the restarted manager
docker swarm unlock
Please enter unlock key: <enter your key>
Leave a swarm. Run on swarm managers, last
docker swarm leave -f
53. Run from any manager to prevent it from running user app
docker node update --availability drain mgr1
54. deploy as swarm service, replicate mode. For Global mode, avoid —replicas and
user “—mode global”
docker service create --name web-fe \
-p 8080:8080 \
--replicas 5 \
nigelpoulton/ddd-book:web0.1
Create service in swarm in host mode
docker service create -d --name svc1 \
--publish published=5005,target=80,mode=host \
nginx
55. List all services in swarm
docker service ls
56. List of service replicas and their state
docker service ps web-fe
57. Detailed information about a service. For more information avoid —pretty flag docker service inspect --pretty web-fe
58. Scal replicas from 5 to 10 for a service
docker service scale web-fe=10
59. Delete service, doesn’t ask for confirmation docker service rm web-fe
60. Create overlay docker network create -d overlay uber-net
Create overlay network from between subnet
docker network create --subnet=10.1.1.0/24 --subnet=11.1.1.0/24 -d overlay prod-net
docker service create --name uber-svc \
--network uber-net \
-p 8080:8080 --replicas 12 \
nigelpoulton/ddd-book:web0.1
61. Update replicas with new changes
docker service update \
--image nigelpoulton/ddd-book:web0.2 \
--update-parallelism 2 \
--update-delay 20s \
uber-svc
62. gathers log from very replica and display them in single output,
For container logs docke logs <container_name>
In Swarm
docker service logs
—flag: follow logs
—tail: tail logs
—details: details information
docker service logs
daemon & service log can be seen depends on which init system you’re using. If you’re
running a “systemd”, Docker will post logs to journald and you can view them with
the “journalctl -u docker.service” command. If you’re using a different init system, you
might want to check the following locations:
·
·
·
Ubuntu systems running upstart: /var/log/upstart/docker.log
RHEL-based systems: /var/log/messages
Debian: /var/log/daemon.log
For windows container, Windows Event Viewer or directly in ~\AppData\Local\Docker
tell Docker how verbose you want daemon logging to be. To do this, edit the daemon
config file at “/etc/docker/daemon.json” and set "debug" to "true" and "log-level" to
one of the following:
·
debug – the most verbose option
·
info – the default value and second-most verbose option
·
warn – third most verbose option
·
error – fourth most verbose option
·
fatal – least verbose option
{
<Snip>
"debug":true,
"log-level":"debug",
<Snip>
}
json-file and journald are probably the easiest to configure and they both work with
the docker logs and docker service logs commands.
The following snippet from a daemon.json shows a Docker host configured to
use journald.
{
"log-driver": "journald"
}
can also start a container or a service with the --log-driver and --log-opts flags to
override the settings in daemon.json.
64. Stack combine Compose and Swarm to create a platform for easy deployment and
management of complex multi-container apps on secure, highly available infrastructure
basic form it accepts two arguments:
·
The name of the stack file (Compose file)
·
The name of the stack (app)
docker stack deploy -c compose.yaml ddd
65. docker stack ls - prints a list of running stacks and how many services they have
66. docker stack ps <stack-name> - gives more detailed information about a specific
stack and its replicas, Stack-name is name of the app
67. docker stack rm deletes a stack and doesn’t ask for confirmation
68. docker volume rm ddd_counter-vol // run this command ton every swarm node that
hosted a replica.
69. docker network rm <network_name>
70. docker volume create myvol //create a new volume called myvol.
docker volume ls//list existing volumes
docker volume inspect myvol//
docker volume prune//deletes all volumes not mounted into a container or service
replica, so use it with caution!
docker volume prune -all//will remove all local volumes not used by at least one
container.
If you specify a volume that already exists, Docker will use it
If you specify a volume that does not exist, Docker will create it
docker run -it --name voltainer --mount source=bizvol,target=/vol alpine//--mount flag,
telling Docker to mount a volume called bizvol into the container at /vol
Type Ctrl PQ to return to your local shell,
ls -l /var/lib/docker/volumes/bizvol/_data/ —from docker host
cat /var/lib/docker/volumes/bizvol/_data/file1 —from docker host
docker volume rm bizvol//can’t delete it, if used by container
71.
check the status of the daemon
Linux systems not using Systemd.
$ service docker status
Linux systems using Systemd.
$ systemctl is-active docker
active
72. configure the certificate rotation period
docker swarm update --cert-expiry 720h
73. docker swarm ca command to manage other CA-related settings.
docker swarm ca --help
74.
docker scout quickview nigelpoulton/tu-demo:latest
docker scout cves nigelpoulton/tu-demo:latest//detailed info
75. Command to generate key pair. new key pair called nigel and loads it to the local
trust store ready for use. It will prompt you to enter a passphrase; don’t forget it :-)
docker trust key generate nigel
76.docker trust key load key.pem --name nigel. //already have a key pair, you can
import and load it with this command
77. docker trust signer add --key nigel.pub nigel nigelpoulton/ddd-trust —example
associates the nigel.pub key with the nigelpoulton/ddd-trust repo on Docker Hub
78.docker trust sign nigelpoulton/ddd-trust:signed —signs a local image
called nigelpoulton/ddd-trust:signed and pushes it to Docker Hub
77. docker trust inspect nigelpoulton/ddd-trust:signed --pretty //inspect signing data of
image.
78. export DOCKER_CONTENT_TRUST=1 //force a Docker host to sign and verify all
images.
79. unset DOCKER_CONTENT_TRUST //disable Docker Content Trust, need to run it
on every node where you enabled Docker Content Trust.
80. docker trust signer remove nigel nigelpoulton/ddd-trust —Remove the signer from
the repository you created
Download