Docker – Commandes utiles

Commande : docker
Usage:	docker COMMAND

A self-sufficient runtime for containers

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

Management Commands:
  config      Manage Docker configs
  container   Manage containers
  image       Manage images
  network     Manage networks
  node        Manage Swarm nodes
  plugin      Manage plugins
  secret      Manage Docker secrets
  service     Manage services
  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

 

DOCKER CONTAINER

Commande : docker container
Usage:	docker container COMMAND

Manage containers

Options:


Commands:
  attach      Attach local standard input, output, and error streams to a running container
  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
  exec        Run a command in a running container
  export      Export a container's filesystem as a tar archive
  inspect     Display detailed information on one or more containers
  kill        Kill one or more running containers
  logs        Fetch the logs of a container
  ls          List containers
  pause       Pause all processes within one or more containers
  port        List port mappings or a specific mapping for the container
  prune       Remove all stopped containers
  rename      Rename a container
  restart     Restart one or more containers
  rm          Remove one or more containers
  run         Run a command in a new container
  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
  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
  wait        Block until one or more containers stop, then print their exit codes

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

 

DOCKER CONTAINER ATTACH

Commande : docker container attach
Usage:	docker container attach [OPTIONS] CONTAINER

Attach local standard input, output, and error streams to a running container

Options:
      --detach-keys string   Override the key sequence for detaching a container
      --no-stdin             Do not attach STDIN
      --sig-proxy            Proxy all received signals to the process (default true)

 

Attacher un container en background au terminal de l’hôte :

Un container peut être détaché et être mis en background avec Ctrl + p + q. La commande suivante permet de le réattacher.

docker container attach container

Equivaut à :
docker attach container
 

DOCKER CONTAINER COMMIT

Commande : docker container commit
Usage:	docker container commit [OPTIONS] CONTAINER [REPOSITORY[:TAG]]

Create a new image from a container's changes

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

 

Commiter un container pour générer une image en vue d’un push :

docker container commit [-p] [-m "message"] src-container dst-image

L’option -p met en pause le container durant le commit, l’option -m définit un message de commit.
Equivaut à :
docker commit [-p] [-m "message"] src-container dst-image
ex :

$ docker commit -p -m "Initial commit v1.0" web_server darwinos/repotest:web_server-v1.0
sha256:473db7bf6771b5b246d860a5e489c3c564598921702e3c1e36e67bc4a5d44295
$ docker push darwinos/repotest:web_server-v1.0
The push refers to repository [docker.io/darwinos/repotest]
0a8166724d0c: Pushed 
f12c6cf07176: Mounted from library/nginx 
341dde1390a8: Mounted from library/nginx 
9c46f426bcb7: Mounted from library/nginx 
web_server-v1.0: digest: sha256:94c8c9e02f97ddc1fcd1000297415a0c0164068d924e36452c32cf930b02dbde size: 1155

 

DOCKER CONTAINER DIFF

Commande : docker container diff
Usage:	docker container diff CONTAINER

Inspect changes to files or directories on a container's filesystem

 

Afficher les fichiers modifiés sur le système de fichier d’un container spécifié :

A pour Ajout
C pour Modification
D pour Suppression

docker container diff container

Equivaut à :
docker diff container
ex :

$ docker container diff example-voting-app_vote_1
C /usr
C /usr/local
C /usr/local/lib
C /usr/local/lib/python2.7
A /usr/local/lib/python2.7/uuid.pyc
A /usr/local/lib/python2.7/difflib.pyc
C /usr/local/lib/python2.7/email
C /usr/local/lib/python2.7/email/mime
A /usr/local/lib/python2.7/email/mime/audio.pyc
A /usr/local/lib/python2.7/email/mime/text.pyc
A /usr/local/lib/python2.7/email/mime/message.pyc
A /usr/local/lib/python2.7/email/mime/nonmultipart.pyc
A /usr/local/lib/python2.7/email/mime/base.pyc
A /usr/local/lib/python2.7/email/mime/image.pyc
A /usr/local/lib/python2.7/email/mime/multipart.pyc
A /usr/local/lib/python2.7/imghdr.pyc
A /usr/local/lib/python2.7/code.pyc
A /usr/local/lib/python2.7/BaseHTTPServer.pyc
A /usr/local/lib/python2.7/sndhdr.pyc
A /usr/local/lib/python2.7/decimal.pyc
A /usr/local/lib/python2.7/codeop.pyc
C /usr/local/lib/python2.7/ctypes
A /usr/local/lib/python2.7/ctypes/util.pyc

 

DOCKER CONTAINER EXEC

Commande : docker container exec
Usage:	docker container exec [OPTIONS] CONTAINER COMMAND [ARG...]

Run a command in a running container

Options:
  -d, --detach               Detached mode: run command in the background
      --detach-keys string   Override the key sequence for detaching a container
  -e, --env list             Set environment variables
  -i, --interactive          Keep STDIN open even if not attached
      --privileged           Give extended privileges to the command
  -t, --tty                  Allocate a pseudo-TTY
  -u, --user string          Username or UID (format: [:])
  -w, --workdir string       Working directory inside the container

 

Exécuter une commande sur un container en cours d’exécution :

docker container exec [options] container command [arg...]

Equivaut à :
docker exec [options] container command [arg...]
ex :
Exécuter un ping en foreground sur le container nommé test :

$ docker container exec test /bin/bash -c 'ping -c 3 8.8.8.8'
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=55 time=19.6 ms
64 bytes from 8.8.8.8: icmp_seq=2 ttl=55 time=18.2 ms
64 bytes from 8.8.8.8: icmp_seq=3 ttl=55 time=24.1 ms

--- 8.8.8.8 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2002ms
rtt min/avg/max/mdev = 18.204/20.662/24.160/2.542 ms

Exécuter un ping en background sur le container nommé test :

$ docker container exec -d test /bin/bash -c 'ping -c 3 8.8.8.8'
$

Exécuter un bash en attachant le container nommé test :

$ docker container exec -it test /bin/bash
root@863dc06b964a:/# 

 

DOCKER CONTAINER INSPECT

Commande : docker container inspect
Usage:	docker container inspect [OPTIONS] CONTAINER [CONTAINER...]

Display detailed information on one or more containers

Options:
  -f, --format string   Format the output using the given Go template
  -s, --size            Display total file sizes

 

Afficher la configuration d’un container :

docker container inspect [-f '["Texte"] {{[json] .Path.To.Information}}'] container

Equivaut à :
docker inspect --type="container" [-f '["Texte"] {{[json] .Path.To.Information}}'] object
Pour plus d’informations : Docker Docs – Format command and log output
ex :

$ docker container inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' youthful_wozniak
172.17.0.2
$ docker container inspect -f 'MAC address : {{range .NetworkSettings.Networks}}{{.MacAddress}}{{end}}' youthful_wozniak
MAC address : 02:42:ac:11:00:02
$ docker container inspect -f '{{.LogPath}}' youthful_wozniak
/var/lib/docker/containers/a624e8d3eadfc974f5d5534e1e7f10ba10b69dc5d8ee9f8c53f8477b8eb127c4/a624e8d3eadfc974f5d5534e1e7f10ba10b69dc5d8ee9f8c53f8477b8eb127c4-json.log
$ docker container inspect -f '{{.Config.Image}}' youthful_wozniak
darwinos/repotest:web_server-v1.0
$ docker container inspect -f '{{json .Config}}' youthful_wozniak
{"Hostname":"a624e8d3eadf","Domainname":"","User":"","AttachStdin":false,"AttachStdout":true,"AttachStderr":true,"ExposedPorts":{"80/tcp":{}},"Tty":false,"OpenStdin":false,"StdinOnce":false,"Env":["PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin","NGINX_VERSION=1.15.0-1~stretch","NJS_VERSION=1.15.0.0.2.1-1~stretch"],"Cmd":["nginx","-g","daemon off;"],"ArgsEscaped":true,"Image":"darwinos/repotest:web_server-v1.0","Volumes":null,"WorkingDir":"","Entrypoint":null,"OnBuild":null,"Labels":{"maintainer":"NGINX Docker Maintainers "},"StopSignal":"SIGTERM"}
$ docker container inspect -f '{{.Config}}' youthful_wozniak
{a624e8d3eadf   false true true map[80/tcp:{}] false false false [PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin NGINX_VERSION=1.15.0-1~stretch NJS_VERSION=1.15.0.0.2.1-1~stretch] [nginx -g daemon off;]  true darwinos/repotest:web_server-v1.0 map[]  [] false  [] map[maintainer:NGINX Docker Maintainers ] SIGTERM  []}
$ docker container inspect -f '{{ json .GraphDriver }}' c1 | jq
{
  "Data": {
    "LowerDir": "/var/lib/docker/overlay2/33d48d040eabd0501c2b4c472665b1943604c5c3cd9520f7553652242e314fbe-init/diff:/var/lib/docker/overlay2/205b956c7af855baadb58e88d4c82f342dc735e9804c6ad842da64775940d461/diff",
    "MergedDir": "/var/lib/docker/overlay2/33d48d040eabd0501c2b4c472665b1943604c5c3cd9520f7553652242e314fbe/merged",
    "UpperDir": "/var/lib/docker/overlay2/33d48d040eabd0501c2b4c472665b1943604c5c3cd9520f7553652242e314fbe/diff",
    "WorkDir": "/var/lib/docker/overlay2/33d48d040eabd0501c2b4c472665b1943604c5c3cd9520f7553652242e314fbe/work"
  },
  "Name": "overlay2"
}
$ docker container inspect --format '{{ .Id }}' 450475a
450475ae3fd3332d7fd8a1d6dfcdcf43bd202f8458f0f1182b72fa73d6399fb1
$ docker container inspect --format '{{ .NetworkSettings.IPAddress }}' 450475a
172.17.0.2
$ docker container inspect --format '{{ json .State }}' hardcore_heisenberg
{"Status":"running","Running":true,"Paused":false,"Restarting":false,"OOMKilled":false,"Dead":false,"Pid":11579,"ExitCode":0,"Error":"","StartedAt":"2018-10-11T15:15:04.684322824Z","FinishedAt":"0001-01-01T00:00:00Z"}
$ docker container inspect --format '{{ json .State }}' hardcore_heisenberg | jq
{
  "Status": "running",
  "Running": true,
  "Paused": false,
  "Restarting": false,
  "OOMKilled": false,
  "Dead": false,
  "Pid": 11579,
  "ExitCode": 0,
  "Error": "",
  "StartedAt": "2018-10-11T15:15:04.684322824Z",
  "FinishedAt": "0001-01-01T00:00:00Z"
}
$ docker container inspect --format '{{ json .State }}' hardcore_heisenberg | python -m json.tool
{
  "Status": "running",
  "Running": true,
  "Paused": false,
  "Restarting": false,
  "OOMKilled": false,
  "Dead": false,
  "Pid": 11579,
  "ExitCode": 0,
  "Error": "",
  "StartedAt": "2018-10-11T15:15:04.684322824Z",
  "FinishedAt": "0001-01-01T00:00:00Z"
}

 

DOCKER CONTAINER KILL

Commande : docker container kill
Usage:	docker container kill [OPTIONS] CONTAINER [CONTAINER...]

Kill one or more running containers

Options:
  -s, --signal string   Signal to send to the container (default "KILL")

 

Tuer un container en exécution :

docker container kill [OPTIONS] container [container ...]

Equivaut à :
docker kill [OPTIONS] container [container ...]
 

DOCKER CONTAINER LOGS

Commande : docker container logs
Usage:	docker container logs [OPTIONS] CONTAINER

Fetch the logs of a container

Options:
      --details        Show extra details provided to logs
  -f, --follow         Follow log output
      --since string   Show logs since timestamp (e.g. 2013-01-02T13:23:37) or relative (e.g. 42m for 42 minutes)
      --tail string    Number of lines to show from the end of the logs (default "all")
  -t, --timestamps     Show timestamps
      --until string   Show logs before a timestamp (e.g. 2013-01-02T13:23:37) or relative (e.g. 42m for 42 minutes)

 

Afficher les logs d’un container :

docker container logs [-f] [--tail="N"] container

Option -f pour affichage en temps réel et option --tail pour définir le nombre de lignes de logs à afficher.
Les logs affichés correspondent à un fichier de logs au format JSON (Logging Driver par défaut : json-file) généré pour chaque container :
/var/lib/docker/containers/CONTAINER_ID/CONTAINER_ID-json.log
Equivaut à :
docker logs [-f] [--tail="N"] container
ex :

$ docker container logs mysql
error: database is uninitialized and password option is not specified 
  You need to specify one of MYSQL_ROOT_PASSWORD, MYSQL_ALLOW_EMPTY_PASSWORD and MYSQL_RANDOM_ROOT_PASSWORD

Rmq :
Pour lancer un container avec un driver de logs différent du driver par défaut (ci-dessous pour utiliser le driver syslog) :

docker container run --log-driver syslog --log-opt syslog-address=udp://log_server:123 ...

 

DOCKER CONTAINER LS

Commande : docker container ls
Usage:	docker container ls [OPTIONS]

List containers

Aliases:
  ls, ps, list

Options:
  -a, --all             Show all containers (default shows just running)
  -f, --filter filter   Filter output based on conditions provided
      --format string   Pretty-print containers using a Go template
  -n, --last int        Show n last created containers (includes all states) (default -1)
  -l, --latest          Show the latest created container (includes all states)
      --no-trunc        Don't truncate output
  -q, --quiet           Only display numeric IDs
  -s, --size            Display total file sizes

 

Afficher la liste des containers actifs :

docker container ls

Equivaut à :
docker ps
docker container ps
ex :

$ docker container ls
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                     NAMES
43e5686848da        training/webapp     "python app.py"          13 minutes ago      Up 13 minutes       0.0.0.0:32769->5000/tcp   web_server
88858662f6a8        training/postgres   "su postgres -c '/us…"   4 hours ago         Up 4 hours          5432/tcp                  pgdb

 

Afficher la liste de tous les containers, actifs et inactifs :

docker container ls -a

Equivaut à :
docker ps -a
docker container ps -a
 

Afficher la liste des IDs de tous les containers, actifs et inactifs :

docker container ls -aq

Equivaut à :
docker ps -aq
docker container ps -aq
ex :

$ docker container ls -aq
43e5686848da
88858662f6a8
c2c11cbd83c8
54823789ede4

 

Afficher la liste des X derniers containers :

docker container ls -n X

Equivaut à :
docker ps -n X
docker container ps -n X
 

Afficher le dernier container :

docker container ls -l

Equivaut à :
docker ps -l
docker container ps -l
docker ps -n 1
docker container ps -n 1
docker container ls -n 1
 

DOCKER CONTAINER PAUSE

Commande : docker container pause
Usage:	docker container pause CONTAINER [CONTAINER...]

Pause all processes within one or more containers

 

Mettre en pause un container en exécution :

docker container pause container [container ...]

Equivaut à :
docker pause container [container ...]
 

DOCKER CONTAINER PORT

Commande : docker container port
Usage:	docker container port CONTAINER [PRIVATE_PORT[/PROTO]]

List port mappings or a specific mapping for the container

 

Afficher le mappage de ports pour un container spécifié :

docker container port container

Equivaut à :
docker port container
ex :

$ docker container port example-voting-app_result_1
80/tcp -> 0.0.0.0:5001
5858/tcp -> 0.0.0.0:5858

 

DOCKER CONTAINER RM

Commande : docker container rm
Usage:	docker container rm [OPTIONS] CONTAINER [CONTAINER...]

Remove one or more containers

Options:
  -f, --force     Force the removal of a running container (uses SIGKILL)
  -l, --link      Remove the specified link
  -v, --volumes   Remove the volumes associated with the container

 

Supprimer un container inactif :

docker container rm [OPTIONS] container [container ...]

Forcer la suppression avec l’option -f.
Supprimer les volumes associés au container avec l’option -v.
Equivaut à :
docker rm [OPTIONS] container [container ...]
ex :

$ docker container rm c2c11cbd83c8
c2c11cbd83c8
$ docker container rm nginxos
nginxos

 

Supprimer tous les containers (actifs comme inactifs) :

docker container rm $(docker container stop $(docker container ls -aq))

ou

docker container stop $(docker container ls -aq)
docker container rm $(docker container ls -aq)

Equivaut à :
docker container rm $(docker container stop $(docker container ls -aq))
ou
docker container rm -f $(docker container ls -aq)
ou
docker stop $(docker ps -aq)
docker rm $(docker ps -aq)

ou
docker rm $(docker stop $(docker ps -aq))
ou
docker rm -f $(docker ps -aq)
ex :

$ docker container rm $(docker container stop $(docker container ls -aq))
50243ad842c6
c482371ecc18
ea820957528a
28ee34748360
7fa9fcc488c9
9004213ea760

 

DOCKER CONTAINER RUN

Commande : docker container run
Usage:	docker container run [OPTIONS] IMAGE [COMMAND] [ARG...]

Run a command in a new container

Options:
      --add-host list                  Add a custom host-to-IP mapping (host:ip)
  -a, --attach list                    Attach to STDIN, STDOUT or STDERR
      --blkio-weight uint16            Block IO (relative weight), between 10 and 1000, or 0 to disable (default 0)
      --blkio-weight-device list       Block IO weight (relative device weight) (default [])
      --cap-add list                   Add Linux capabilities
      --cap-drop list                  Drop Linux capabilities
      --cgroup-parent string           Optional parent cgroup for the container
      --cidfile string                 Write the container ID to the file
      --cpu-period int                 Limit CPU CFS (Completely Fair Scheduler) period
      --cpu-quota int                  Limit CPU CFS (Completely Fair Scheduler) quota
      --cpu-rt-period int              Limit CPU real-time period in microseconds
      --cpu-rt-runtime int             Limit CPU real-time runtime in microseconds
  -c, --cpu-shares int                 CPU shares (relative weight)
      --cpus decimal                   Number of CPUs
      --cpuset-cpus string             CPUs in which to allow execution (0-3, 0,1)
      --cpuset-mems string             MEMs in which to allow execution (0-3, 0,1)
  -d, --detach                         Run container in background and print container ID
      --detach-keys string             Override the key sequence for detaching a container
      --device list                    Add a host device to the container
      --device-cgroup-rule list        Add a rule to the cgroup allowed devices list
      --device-read-bps list           Limit read rate (bytes per second) from a device (default [])
      --device-read-iops list          Limit read rate (IO per second) from a device (default [])
      --device-write-bps list          Limit write rate (bytes per second) to a device (default [])
      --device-write-iops list         Limit write rate (IO per second) to a device (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
      --entrypoint string              Overwrite the default ENTRYPOINT of the image
  -e, --env list                       Set environment variables
      --env-file list                  Read in a file of environment variables
      --expose list                    Expose a port or a range of ports
      --group-add list                 Add additional groups to join
      --health-cmd string              Command to run to check health
      --health-interval duration       Time between running the check (ms|s|m|h) (default 0s)
      --health-retries int             Consecutive failures needed to report unhealthy
      --health-start-period duration   Start period for the container to initialize before starting health-retries countdown (ms|s|m|h) (default 0s)
      --health-timeout duration        Maximum time to allow one check to run (ms|s|m|h) (default 0s)
      --help                           Print usage
  -h, --hostname string                Container host name
      --init                           Run an init inside the container that forwards signals and reaps processes
  -i, --interactive                    Keep STDIN open even if not attached
      --ip string                      IPv4 address (e.g., 172.30.100.104)
      --ip6 string                     IPv6 address (e.g., 2001:db8::33)
      --ipc string                     IPC mode to use
      --isolation string               Container isolation technology
      --kernel-memory bytes            Kernel memory limit
  -l, --label list                     Set meta data on a container
      --label-file list                Read in a line delimited file of labels
      --link list                      Add link to another container
      --link-local-ip list             Container IPv4/IPv6 link-local addresses
      --log-driver string              Logging driver for the container
      --log-opt list                   Log driver options
      --mac-address string             Container MAC address (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' to enable unlimited swap
      --memory-swappiness int          Tune container memory swappiness (0 to 100) (default -1)
      --mount mount                    Attach a filesystem mount to the container
      --name string                    Assign a name to the container
      --network string                 Connect a container to a network (default "default")
      --network-alias list             Add network-scoped alias for the container
      --no-healthcheck                 Disable any container-specified HEALTHCHECK
      --oom-kill-disable               Disable OOM Killer
      --oom-score-adj int              Tune host's OOM preferences (-1000 to 1000)
      --pid string                     PID namespace to use
      --pids-limit int                 Tune container pids limit (set -1 for unlimited)
      --privileged                     Give extended privileges to this container
  -p, --publish list                   Publish a container's port(s) to the host
  -P, --publish-all                    Publish all exposed ports to random ports
      --read-only                      Mount the container's root filesystem as read only
      --restart string                 Restart policy to apply when a container exits (default "no")
      --rm                             Automatically remove the container when it exits
      --runtime string                 Runtime to use for this container
      --security-opt list              Security Options
      --shm-size bytes                 Size of /dev/shm
      --sig-proxy                      Proxy received signals to the process (default true)
      --stop-signal string             Signal to stop a container (default "SIGTERM")
      --stop-timeout int               Timeout (in seconds) to stop a container
      --storage-opt list               Storage driver options for the container
      --sysctl map                     Sysctl options (default map[])
      --tmpfs list                     Mount a tmpfs directory
  -t, --tty                            Allocate a pseudo-TTY
      --ulimit ulimit                  Ulimit options (default [])
  -u, --user string                    Username or UID (format: [:])
      --userns string                  User namespace to use
      --uts string                     UTS namespace to use
  -v, --volume list                    Bind mount a volume
      --volume-driver string           Optional volume driver for the container
      --volumes-from list              Mount volumes from the specified container(s)
  -w, --workdir string                 Working directory inside the container

 

Exécuter un container à partir d’une image :

docker container run [options] image [command] [arg...]

Equivaut à :
docker run [options] image [command] [arg...]
ex :
Lancer la dernière image Ubuntu dans un container nommé test (--name) avec un pseudo-terminal TTY (-t) interactif (-i pour garder le flux d’entrée STDIN ouvert) :

$ docker container run -it --name test ubuntu:latest
Unable to find image 'ubuntu:latest' locally
latest: Pulling from library/ubuntu
6b98dfc16071: Pull complete 
4001a1209541: Pull complete 
6319fc68c576: Pull complete 
b24603670dc3: Pull complete 
97f170c87c6f: Pull complete 
Digest: sha256:5f4bdc3467537cbbe563e80db2c3ec95d548a9145d64453b06939c4592d67b6d
Status: Downloaded newer image for ubuntu:latest
root@e742e2517dac:/#

 

Exécuter un container en arrière-plan et afficher son ID :

docker container run -d [options] image [command] [arg...]

ou

docker container run --detach [options] image [command] [arg...]

 

Mapper manuellement (publier) un port exposé du container vers un port défini de l’hôte Docker :

docker container run -p phost:pguest [options] image [command] [arg...]

ou

docker container run --publish phost:pguest [options] image [command] [arg...]

ex :

$ docker container run -d --name web_server -p 8080:80 nginx

 

Mapper automatiquement (publier) un port exposé du container vers un port aléatoirement déterminé de l’hôte Docker :

docker container run -P [options] image [command] [arg...]

ou

docker container run --publish-all [options] image [command] [arg...]

ex :

$ docker container run -d --name web_server -P nginx

 

Exécuter un container à partir d’une image et le supprimer une fois arrêté :

docker container run --rm [options] image [command] [arg...]

Equivaut à :
docker run --rm [options] image [command] [arg...]
 

Exécuter un container à partir d’une image sur un réseau spécifique :

docker container run --network network [options] image [command] [arg...]

Equivaut à :
docker run --network network [options] image [command] [arg...]
 

Utiliser un volume nommé lors du lancement d’un container :

Rmq : Si le volume n’a pas été créé au préalable avec la commande docker volume create,il sera créé (de type driver local).
Le contenu du dossier destination (donc du container) sera copié dans le dossier source (donc de l’hôte).

docker container run --volume volume:/path/to/container-dir:[ro] [options] image [command] [arg...]

ou

docker container run --mount [type=volume,]source=volume,destination=/path/to/container-dir[,readonly] [options] image [command] [arg...]

Equivaut à :
docker run --volume volume:/path/to/container-dir:[ro] [options] image [command] [arg...]
ou
docker run --mount [type=volume,]source=volume,destination=/path/to/container-dir[,readonly] [options] image [command] [arg...]
ex :

$ docker volume create html
html
$ docker container run -d --name www --volume html:/usr/share/nginx/html nginx
Unable to find image 'nginx:latest' locally
latest: Pulling from library/nginx
f17d81b4b692: Pull complete 
d5c237920c39: Pull complete 
a381f92f36de: Pull complete 
Digest: sha256:5704bcdeec8715eb71c95a425f4c4a14264d8c6f92a0b105c23933a2eb503b63
Status: Downloaded newer image for nginx:latest
3e8631ae4ec938e9773cbd1c2954398cc762774299f365505e05dafa41fd2ad6
$ sudo ls /var/lib/docker/volumes/html/_data
50x.html  index.html
$ docker container exec www mount | grep 'html'
/dev/sda1 on /usr/share/nginx/html type ext4 (rw,relatime,errors=remount-ro,data=ordered)
$ sudo touch /var/lib/docker/volumes/html/_data/fromhost.txt
$ docker container exec www ls -l /usr/share/nginx/html/
total 8
-rw-r--r-- 1 root root 494 Oct  2 14:49 50x.html
-rw-r--r-- 1 root root   0 Oct 16 22:52 fromhost.txt
-rw-r--r-- 1 root root 612 Oct  2 14:49 index.html
$ docker container run -ti --mount source=bin,destination=/hostbin,readonly alpine sh

 

Créer un volume de type volume anonyme à la création du container :

Le mappage du volume peut correspondre aussi bien à un mappage de deux dossiers qu’à un mappage de deux fichiers.
Le contenu du dossier destination (donc du container) sera copié dans le dossier source (donc de l’hôte).

docker container run --volume /path/to/container-dir [options] image [command] [arg...]

ou

docker container run --mount [type=volume,]destination=/path/to/container-dir [options] image [command] [arg...]

Equivaut à :
docker run --volume /path/to/container-dir [options] image [command] [arg...]
ou
docker run --mount [type=volume,]destination=/path/to/container-dir [options] image [command] [arg...]
ex :

$ docker container run -d --volume /usr/share/nginx/html nginx
$ docker container run -ti --mount destination=/hostbin alpine sh

 

Créer un volume de type bind à la création du container :

Le mappage du volume peut correspondre aussi bien à un mappage de deux dossiers qu’à un mappage de deux fichiers.
Le contenu du dossier source (donc de l’hôte) sera copié dans le dossier destination (donc du container).

docker container run --volume /path/to/host-dir:/path/to/container-dir:[ro] [options] image [command] [arg...]

ou

docker container run --mount [type=bind,]source=/path/to/host-dir,destination=/path/to/container-dir[,readonly] [options] image [command] [arg...]

Equivaut à :
docker run --volume /path/to/host-dir:/path/to/container-dir:[ro] [options] image [command] [arg...]
ou
docker run --mount [type=bind,]source=/path/to/host-dir,destination=/path/to/container-dir[,readonly] [options] image [command] [arg...]
ex :

$ docker container run -d --volume /home/adminsys/docker/html:/usr/share/nginx/html nginx
$ docker container run -d --volume /tmp/index.html:/usr/share/nginx/html/index.html -p 8080:80 nginx
$ docker container run -d --volume /var/run/docker.sock:/var/run/docker.sock nginx
$ docker container run -ti --mount type=bind,source=/bin,destination=/hostbin,readonly alpine sh

 

Effectuer un healthcheck à l’exécution d’un container

docker container run [OPTIONS] --health-cmd="command" [--health-interval=T]  [--health-retries=N] [--health-timeout=T] [--health-start-period=T] [--no-healthcheck] image [command] [arg...]
  • --health-cmd : Command to run to check health
  • --health-interval : Time between running the check (default 30s)
  • --health-retries : Consecutive failures needed to report unhealthy (default 3)
  • --health-timeout : Maximum time to allow one check to run (default 30s)
  • --health-start-period : Start period for the container to initialize before starting health-retries countdown (defaut 0s)
  • --no-healthcheck : Disable any container-specified HEALTHCHECK

ex :

$ docker container run \
  --health-cmd="curl -f localhost:9200/_cluster/health || false" \
  --health-interval=5s \
  --health-retries=3 \
  --health-timeout=2s \
  --health-start-period=15s \
elasticsearch:2
f93272d7b6617cc62f34d957d2da54b99a7267f0a9f9146c73b91aebb7195f2a
$ docker container ls
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                    PORTS                NAMES
f93272d7b661        elasticsearch:2     "/docker-entrypoint.…"   26 seconds ago      Up 24 seconds (healthy)   9200/tcp, 9300/tcp   mystifying_kirch
$ docker container inspect --format='{{.State.Health.Status}}' f93272d7b661
healthy

Rmq : false peut être remplacé par exit 1.

DOCKER CONTAINER START

Commande : docker container start
Usage:	docker container start [OPTIONS] CONTAINER [CONTAINER...]

Start one or more stopped containers

Options:
  -a, --attach               Attach STDOUT/STDERR and forward signals
      --detach-keys string   Override the key sequence for detaching a container
  -i, --interactive          Attach container's STDIN

 

Démarrer un container inactif :

docker container start [OPTIONS] container [container ...]

Equivaut à :
docker start [OPTIONS] container [container ...]
ex :

$ docker start 1193c88a9b75
1193c88a9b75
$ docker start tender_panini
tender_panini

 

Démarrer un bash sur container inactif :

Si le container avait initialement été créé avec un bash interactif, il est possible de reprendre la main sur lui en le démarrant avec les options suivantes :
-a : attacher la sortie standard et la sortie erreur au container
-i : attacher l’entrée standard au container

docker container start -ai container [container ...]

Equivaut à :
docker start -ai container [container ...]
ex :

$ docker container run -it --name ubuntu ubuntu
root@529052b0a6fe:/# exit
exit
$ docker container ls -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                      PORTS               NAMES
529052b0a6fe        ubuntu              "/bin/bash"         22 seconds ago      Exited (0) 14 seconds ago                       ubuntu
$ docker container start -ai ubuntu
root@529052b0a6fe:/# read escape sequence # ici combinaison Ctrl + p + q pour se détacher du container
$ docker container ls -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
529052b0a6fe        ubuntu              "/bin/bash"         42 seconds ago      Up 8 seconds                            ubuntu
$ docker container stop ubuntu
ubuntu
$ docker container start ubuntu
ubuntu
$ docker container ls -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
529052b0a6fe        ubuntu              "/bin/bash"         2 minutes ago       Up 5 seconds                            ubuntu

 

Démarrer tous les containers inactifs :

docker container start $(docker container ps -aq)

Equivaut à :
docker start $(docker ps -aq)
 

DOCKER CONTAINER STATS

Commande : docker container stats
Usage:	docker container stats [OPTIONS] [CONTAINER...]

Display a live stream of container(s) resource usage statistics

Options:
  -a, --all             Show all containers (default shows just running)
      --format string   Pretty-print images using a Go template
      --no-stream       Disable streaming stats and only pull the first result
      --no-trunc        Do not truncate output

 

Afficher la consommation des containers en cours d’exécution en temps réel :

docker container stats [container ...]

Equivaut à :
docker stats [container ...]
ex :

$ docker container stats
CONTAINER ID        NAME                CPU %               MEM USAGE / LIMIT     MEM %               NET I/O             BLOCK I/O           PIDS
fb44a4025b18        web_server          0.02%               12.15MiB / 1.957GiB   0.61%               3.08kB / 0B         12.5MB / 0B         1
88858662f6a8        pgdb                0.01%               5.789MiB / 1.957GiB   0.29%               3.3kB / 0B          11.3MB / 35.5MB     7

 

DOCKER CONTAINER STOP

Commande : docker container stop
Usage:	docker container stop [OPTIONS] CONTAINER [CONTAINER...]

Stop one or more running containers

Options:
  -t, --time int   Seconds to wait for stop before killing it (default 10)

 

Stopper un container actif :

docker container stop [OPTIONS] container [container ...]

Equivaut à :
docker stop [OPTIONS] container [container ...]
ex :

$ docker container stop 9e558ecb305b
9e558ecb305b
$ docker container stop dazzling_torvalds
dazzling_torvalds

 

Stopper tous les containers actifs :

docker container stop $(docker container ps -q)

Equivaut à :
docker stop $(docker ps -q)
 

DOCKER CONTAINER TOP

Commande : docker container top
Usage:	docker container top CONTAINER [ps OPTIONS]

Display the running processes of a container

 

Afficher les processus en cours des containers spécifiés :

docker container top container [container...] [ps OPTIONS]

Equivaut à :
docker top container [container...] [ps OPTIONS]
ex :

$ docker container top example-voting-app_vote_1 -faux
USER                PID                 %CPU                %MEM                VSZ                 RSS                 TTY                 STAT                START               TIME                COMMAND
root                29786               0.2                 0.9                 86156               20180               ?                   Ss                  00:52               0:00                | | \_ python app.py
root                30079               1.2                 1.0                 87820               20708               ?                   Sl                  00:52               0:04                | | \_ /usr/local/bin/python app.py

 

DOCKER CONTAINER UNPAUSE

Commande : docker container unpause
Usage:	docker container unpause CONTAINER [CONTAINER...]

Unpause all processes within one or more containers

 

Réactiver un container en pause :

docker container unpause container [container ...]

Equivaut à :
docker unpause container [container ...]
 

DOCKER EVENTS

Commande : docker events
Usage:	docker events [OPTIONS]

Get real time events from the server

Options:
  -f, --filter filter   Filter output based on conditions provided
      --format string   Format the output using the given Go template
      --since string    Show all events created since timestamp
      --until string    Stream events until this timestamp

 

Recevoir les évènements du démon Docker en temps réels :

Les évènements reçus sont émis par les containers, images, plugins, volumes, networks, démons, services, nodes, secrets, configs.
Pour la liste complète des évènements reçus : Docker Docs – docker events

docker events [OPTIONS]

ex :

$ docker events --since '2017-01-05'
2017-01-05T00:35:41.241772953+08:00 volume create testVol (driver=local)
2017-01-05T00:35:58.859401177+08:00 container create d9cd...4d70 (image=alpine:latest, name=test)
2017-01-05T00:36:04.703631903+08:00 network connect e2e1...29e2 (container=0fdb...ff37, name=bridge, type=bridge)
2017-01-05T00:36:04.795031609+08:00 container start 0fdb...ff37 (image=alpine:latest, name=test)
2017-01-05T00:36:09.830268747+08:00 container kill 0fdb...ff37 (image=alpine:latest, name=test, signal=15)
2017-01-05T00:36:09.840186338+08:00 container die 0fdb...ff37 (exitCode=143, image=alpine:latest, name=test)
2017-01-05T00:36:09.880113663+08:00 network disconnect e2e...29e2 (container=0fdb...ff37, name=bridge, type=bridge)
2017-01-05T00:36:09.890214053+08:00 container stop 0fdb...ff37 (image=alpine:latest, name=test)
$ docker events --since '2013-09-03T15:49:29'
$ docker events --since '10m'
$ docker events --since '2017-01-05T00:35:30' --until '2017-01-05T00:36:05'
$ docker events --filter 'event=stop'
$ docker events --filter 'image=alpine'
$ docker events --filter 'container=test'
$ docker events --filter 'container=test' --filter 'container=d9cdb1525ea8'
$ docker events --filter 'container=test' --filter 'event=stop'
$ docker events --filter 'container=container_1' --filter 'container=container_2'
$ docker events --filter 'type=volume'
$ docker events --filter 'type=network'
$ docker events -f type=service
$ docker events -f type=node
$ docker events -f type=secret
$ docker events -f type=config
$ docker events --filter 'scope=swarm'
$ docker events --filter 'type=container' --format 'Type={{.Type}}  Status={{.Status}}  ID={{.ID}}'
$ docker events --format '{{json .}}'

 

DOCKER IMAGE

Commande : docker image
Usage:	docker image COMMAND

Manage images

Options:


Commands:
  build       Build an image from a Dockerfile
  history     Show the history of an image
  import      Import the contents from a tarball to create a filesystem image
  inspect     Display detailed information on one or more images
  load        Load an image from a tar archive or STDIN
  ls          List images
  prune       Remove unused images
  pull        Pull an image or a repository from a registry
  push        Push an image or a repository to a registry
  rm          Remove one or more images
  save        Save one or more images to a tar archive (streamed to STDOUT by default)
  tag         Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE

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

 

DOCKER IMAGE BUILD

Commande : docker image build
Usage:	docker image build [OPTIONS] PATH | URL | -

Build an image from a Dockerfile

Options:
      --add-host list           Add a custom host-to-IP mapping (host:ip)
      --build-arg list          Set build-time variables
      --cache-from strings      Images to consider as cache sources
      --cgroup-parent string    Optional parent cgroup for the container
      --compress                Compress the build context using gzip
      --cpu-period int          Limit the CPU CFS (Completely Fair Scheduler) period
      --cpu-quota int           Limit the CPU CFS (Completely Fair Scheduler) quota
  -c, --cpu-shares int          CPU shares (relative weight)
      --cpuset-cpus string      CPUs in which to allow execution (0-3, 0,1)
      --cpuset-mems string      MEMs in which to allow execution (0-3, 0,1)
      --disable-content-trust   Skip image verification (default true)
  -f, --file string             Name of the Dockerfile (Default is 'PATH/Dockerfile')
      --force-rm                Always remove intermediate containers
      --iidfile string          Write the image ID to the file
      --isolation string        Container isolation technology
      --label list              Set metadata for an image
  -m, --memory bytes            Memory limit
      --memory-swap bytes       Swap limit equal to memory plus swap: '-1' to enable unlimited swap
      --network string          Set the networking mode for the RUN instructions during build (default "default")
      --no-cache                Do not use cache when building the image
      --pull                    Always attempt to pull a newer version of the image
  -q, --quiet                   Suppress the build output and print image ID on success
      --rm                      Remove intermediate containers after a successful build (default true)
      --security-opt strings    Security options
      --shm-size bytes          Size of /dev/shm
  -t, --tag list                Name and optionally a tag in the 'name:tag' format
      --target string           Set the target build stage to build.
      --ulimit ulimit           Ulimit options (default [])

 

Construction d’une image à partir du Dockerfile :

Généralement le Dockerfile se trouve à la racine du contexte (tout comme le .dockerignore).

$ docker image build .

Équivaut à :
$ docker build .
ex :
Avec dockerfiles/Dockerfile

FROM busybox
RUN echo "hello world"
COPY . /home/workfiles/
$ docker image build .
Sending build context to Docker daemon   2.56kB
Step 1/3 : FROM busybox
latest: Pulling from library/busybox
07a152489297: Already exists 
Digest: sha256:141c253bc4c3fd0a201d32dc1f493bcf3fff003b6df416dea4f41046e0f37d47
Status: Downloaded newer image for busybox:latest
 ---> 8c811b4aec35
Step 2/3 : RUN echo "hello world"
 ---> Running in c09167e9ca23
hello world
Removing intermediate container c09167e9ca23
 ---> 36841040c842
Step 3/3 : COPY . /home/workfiles/
 ---> 044398957652
Successfully built 044398957652
$ docker image ls
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
                            4f8e9b900fc0        9 seconds ago       1.15MB
busybox             latest              8c811b4aec35        6 weeks ago         1.15MB
$ docker run -it --name busytest 4f8e9b900fc0
/ # ls /home/workfiles/
essai.txt

Mais il est possible de spécifier le chemin vers le Dockerfile et le contexte, tout en définissant un tag pour l’image :

$ docker image build -f /path/to/Dockerfile -t image:tag /path/to/context-dir/

Équivaut à :
$ docker build -f /path/to/Dockerfile -t image:tag /path/to/context-dir/

  • -t : spécifie le tag de l’image
  • -f : spécifie le fichier à utiliser pour la construction (Dockerfile par défaut)
  • --no-cache : invalide le cache

Le contenu du fichier .dockerignore est ignoré du contexte.
ex :
Avec dockerfiles/Dockerfile

FROM busybox
RUN echo "hello world"
COPY . /home/workfiles/
$ docker image build -f dockerfiles/Dockerfile -t darwinos/repotest:busybox-V1.2 docker/
Sending build context to Docker daemon  2.095kB
Step 1/3 : FROM busybox
latest: Pulling from library/busybox
07a152489297: Pull complete 
Digest: sha256:141c253bc4c3fd0a201d32dc1f493bcf3fff003b6df416dea4f41046e0f37d47
Status: Downloaded newer image for busybox:latest
 ---> 8c811b4aec35
Step 2/3 : RUN echo "hello world"
 ---> Running in 6b6bbf94efeb
hello world
Removing intermediate container 6b6bbf94efeb
 ---> 7d7ff4a1708b
Step 3/3 : COPY . /home/workfiles/
 ---> 79d9a58ba6da
Successfully built 79d9a58ba6da
Successfully tagged darwinos/repotest:busybox-V1.2
$ docker image ls darwinos/repotest:busybox-V1.2
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
darwinos/repotest   busybox-V1.2        79d9a58ba6da        29 seconds ago      1.15MB

On peut ensuite lancer un container à partir de cette image :

$ docker run -it --name busytest darwinos/repotest:busybox-V1.2
/ # ls /home/workfiles/
essai.txt

 

DOCKER IMAGE HISTORY

Commande : docker image history
Usage:	docker image history [OPTIONS] IMAGE

Show the history of an image

Options:
      --format string   Pretty-print images using a Go template
  -H, --human           Print sizes and dates in human readable format (default true)
      --no-trunc        Don't truncate output
  -q, --quiet           Only show numeric IDs

 

Afficher l’historique d’une image :

docker image history image

Equivaut à :
docker history image
ex :

$ docker image history ubuntu
IMAGE               CREATED             CREATED BY                                      SIZE                COMMENT
113a43faa138        3 weeks ago         /bin/sh -c #(nop)  CMD ["/bin/bash"]            0B                  
           3 weeks ago         /bin/sh -c mkdir -p /run/systemd && echo 'do…   7B                  
           3 weeks ago         /bin/sh -c sed -i 's/^#\s*\(deb.*universe\)$…   2.76kB              
           3 weeks ago         /bin/sh -c rm -rf /var/lib/apt/lists/*          0B                  
           3 weeks ago         /bin/sh -c set -xe   && echo '#!/bin/sh' > /…   745B                
           3 weeks ago         /bin/sh -c #(nop) ADD file:28c0771e44ff530db…   81.1MB

 

DOCKER IMAGE INSPECT

Commande : docker image inspect
Usage:	docker image inspect [OPTIONS] IMAGE [IMAGE...]

Display detailed information on one or more images

Options:
  -f, --format string   Format the output using the given Go template

 

Afficher la configuration d’une image:

docker image inspect [-f '["Texte"] {{[json] .Path.To.Information}}'] image

Equivaut à :
docker inspect --type="image" [-f '["Texte"] {{[json] .Path.To.Information}}'] object
Pour plus d’informations : Docker Docs – Format command and log output
ex :

$ docker image inspect -f 'Version de Docker : {{.DockerVersion}}' ubuntu
Version de Docker : 17.06.2-ce

 

DOCKER IMAGE LOAD

Commande : docker image load
Usage:	docker image load [OPTIONS]

Load an image from a tar archive or STDIN

Options:
  -i, --input string   Read from tar archive file, instead of STDIN
  -q, --quiet          Suppress the load output

 

Charger une image depuis une archive tar :

docker image load -i archive.tar

ou

docker image load < archive.tar

Equivaut à :
docker load -i archive.tar
ou
docker load < archive.tar
ex :

$ tar tvf pong-2.0.tar
drwxr-xr-x 0/0               0 2018-10-16 13:22 7d689be2a587c46ff75fe9c0d4058f861444b938460f9f0729fec42dfcdffcd9/
-rw-r--r-- 0/0               3 2018-10-16 13:22 7d689be2a587c46ff75fe9c0d4058f861444b938460f9f0729fec42dfcdffcd9/VERSION
-rw-r--r-- 0/0            1410 2018-10-16 13:22 7d689be2a587c46ff75fe9c0d4058f861444b938460f9f0729fec42dfcdffcd9/json
-rw-r--r-- 0/0            4608 2018-10-16 13:22 7d689be2a587c46ff75fe9c0d4058f861444b938460f9f0729fec42dfcdffcd9/layer.tar
drwxr-xr-x 0/0               0 2018-10-16 13:22 8d153eee9afdd125f452c3e8ea10560a2653a228bc0a7ca4ec856217a50bd5f1/
-rw-r--r-- 0/0               3 2018-10-16 13:22 8d153eee9afdd125f452c3e8ea10560a2653a228bc0a7ca4ec856217a50bd5f1/VERSION
-rw-r--r-- 0/0             482 2018-10-16 13:22 8d153eee9afdd125f452c3e8ea10560a2653a228bc0a7ca4ec856217a50bd5f1/json
-rw-r--r-- 0/0        46928896 2018-10-16 13:22 8d153eee9afdd125f452c3e8ea10560a2653a228bc0a7ca4ec856217a50bd5f1/layer.tar
drwxr-xr-x 0/0               0 2018-10-16 13:22 9855d8e74b5b72748d7841326b8d9741e74523ed46e9ab9a0a8114ffdd579530/
-rw-r--r-- 0/0               3 2018-10-16 13:22 9855d8e74b5b72748d7841326b8d9741e74523ed46e9ab9a0a8114ffdd579530/VERSION
-rw-r--r-- 0/0             482 2018-10-16 13:22 9855d8e74b5b72748d7841326b8d9741e74523ed46e9ab9a0a8114ffdd579530/json
-rw-r--r-- 0/0            2560 2018-10-16 13:22 9855d8e74b5b72748d7841326b8d9741e74523ed46e9ab9a0a8114ffdd579530/layer.tar
drwxr-xr-x 0/0               0 2018-10-16 13:22 cda0fc2f1fa4a75c7ee707f4be247f082923a17ca85dd70f514772079a644f53/
-rw-r--r-- 0/0               3 2018-10-16 13:22 cda0fc2f1fa4a75c7ee707f4be247f082923a17ca85dd70f514772079a644f53/VERSION
-rw-r--r-- 0/0             482 2018-10-16 13:22 cda0fc2f1fa4a75c7ee707f4be247f082923a17ca85dd70f514772079a644f53/json
-rw-r--r-- 0/0         5345792 2018-10-16 13:22 cda0fc2f1fa4a75c7ee707f4be247f082923a17ca85dd70f514772079a644f53/layer.tar
-rw-r--r-- 0/0            4329 2018-10-16 13:22 f501db54c90de1e4cdb9c82f32069fd982f2a8e4f019910371b5a7fc085376ad.json
drwxr-xr-x 0/0               0 2018-10-16 13:22 f89d14af1325a2529c3bb2c704b62f2f2d93a9fb6bb0286ce9defcf5d65028e6/
-rw-r--r-- 0/0               3 2018-10-16 13:22 f89d14af1325a2529c3bb2c704b62f2f2d93a9fb6bb0286ce9defcf5d65028e6/VERSION
-rw-r--r-- 0/0             406 2018-10-16 13:22 f89d14af1325a2529c3bb2c704b62f2f2d93a9fb6bb0286ce9defcf5d65028e6/json
-rw-r--r-- 0/0         5053952 2018-10-16 13:22 f89d14af1325a2529c3bb2c704b62f2f2d93a9fb6bb0286ce9defcf5d65028e6/layer.tar
-rw-r--r-- 0/0             505 1970-01-01 01:00 manifest.json
-rw-r--r-- 0/0              84 1970-01-01 01:00 repositories
$ docker image load -i pong-2.0.tar
Loaded image: pong:2.0
$ docker image ls -a pong:2.0
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
pong                2.0                 f501db54c90d        43 minutes ago      54.1MB

 

DOCKER IMAGE LS

Commande : docker image ls
Usage:	docker image ls [OPTIONS] [REPOSITORY[:TAG]]

List images

Aliases:
  ls, images, list

Options:
  -a, --all             Show all images (default hides intermediate images)
      --digests         Show digests
  -f, --filter filter   Filter output based on conditions provided
      --format string   Pretty-print images using a Go template
      --no-trunc        Don't truncate output
  -q, --quiet           Only show numeric IDs

 

Afficher la liste des images téléchargées ou construites :

docker image ls [image]

Equivaut à :
docker images [image]
ex :

$ docker image ls
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
nginx               latest              5699ececb21c        6 days ago          109MB
debian              latest              9a5d7185d3a6        6 days ago          101MB
ubuntu              latest              113a43faa138        3 weeks ago         81.2MB
centos              latest              49f7960eb7e4        4 weeks ago         200MB
darwinos/repotest   alpine-3.7          3fd9065eaf02        5 months ago        4.15MB
alpine              latest              3fd9065eaf02        5 months ago        4.15MB
training/webapp     latest              6fae60ef3446        3 years ago         349MB
training/postgres   latest              6fa973bb3c26        4 years ago         365MB

 

Afficher la liste des IDs des images taguées et non-taguées (dangling) :

docker image ls -q [image]

Equivaut à :
docker images -q [image]
ex :

$ docker image ls -q
5699ececb21c
9a5d7185d3a6
113a43faa138
49f7960eb7e4
3fd9065eaf02
3fd9065eaf02
6fae60ef3446
6fa973bb3c26

 

Afficher la liste des images taguées ou non-taguées (dangling) ainsi que les images intermédiaires :

docker image ls -a [image]

ou

docker image ls --all [image]

Equivaut à :
docker images -a [image]
ou
docker images --all [image]
 

Afficher les digests des images :

docker image ls --digests [image]

 

DOCKER IMAGE PULL

Commande : docker image pull
Usage:	docker image pull [OPTIONS] NAME[:TAG|@DIGEST]

Pull an image or a repository from a registry

Options:
  -a, --all-tags                Download all tagged images in the repository
      --disable-content-trust   Skip image verification (default true)

 

Télécharger une image depuis le Docker Registry :

docker image pull [user/]image[:tag]

Equivaut à :
docker pull [user/]image[:tag]
ex :

$ docker pull ubuntu:latest

 

DOCKER IMAGE PUSH

Commande : docker image push
Usage:	docker image push [OPTIONS] NAME[:TAG]

Push an image or a repository to a registry

Options:
      --disable-content-trust   Skip image signing (default true)

 

Uploader une image taguée au préalable sur le Docker Registry :

docker image push [user/]image[:tag]

Equivaut à :
docker push [user/]image[:tag]
ex :

$ docker push darwinos/repotest:alpine-3.7

L’image alpine taguée se retrouve ainsi sur le dépôt personnel :

 

DOCKER IMAGE RM

Commande : docker image rm
Usage:	docker image rm [OPTIONS] IMAGE [IMAGE...]

Remove one or more images

Aliases:
  rm, rmi, remove

Options:
  -f, --force      Force removal of the image
      --no-prune   Do not delete untagged parents

 

Supprimer une image :

docker image rm [OPTIONS] image [image ...]

Forcer la suppression avec l’option -f.
Equivaut à :
docker rmi [OPTIONS] image [image ...]
ex :

$ docker image rm 5699ececb21c
Untagged: nginx:latest
Untagged: nginx@sha256:62a095e5da5f977b9f830adaf64d604c614024bf239d21068e4ca826d0d629a4
Deleted: sha256:5699ececb21caf07b92cbda9daa1e965407e3793a72000ecbf6b8e8595a0824a
Deleted: sha256:c34974813e70c230445629bfb7d58dfff99440d9e11fd8aa4230a50c6cb101f3
Deleted: sha256:85dd24921f1b33cd733671fbe604c4630899a19ef3a1822041f4b298636b79ca
Deleted: sha256:9c46f426bcb704beffafc951290ee7fe05efddbc7406500e7d0a3785538b8735

 

Supprimer toutes les images (taguées et non-taguées (dangling)) :

docker image rm $(docker image ls -q)

Equivaut à :
docker rmi $(docker image ls -q)
ex :

$ docker image rm $(docker image ls -q)
Untagged: debian:latest
Untagged: debian@sha256:6ee341d1cf3da8e6ea059f8bc3af9940613c4287205cd71d7c6f9e1718fdcb9b
Deleted: sha256:9a5d7185d3a6ede04c29cf89e4fa879f40e33324ced380decaf8919ffc5a4ade
Deleted: sha256:a2e66f6c6f5f248f2f8dcf31a3b569626ef61c6371e157fb0db857152983fc1d
Untagged: centos:latest
Untagged: centos@sha256:b67d21dfe609ddacf404589e04631d90a342921e81c40aeaf3391f6717fa5322
Deleted: sha256:49f7960eb7e4cb46f1a02c1f8174c6fac07ebf1eb6d8deffbcb5c695f1c9edd5
Deleted: sha256:bcc97fbfc9e1a709f0eb78c1da59caeb65f43dc32cd5deeb12b8c1784e5b8237
[...]

 

Supprimer uniquement les images non-taguées (dangling) :

docker image rm $(docker image ls --filter "dangling=true" -q)

ou

docker image prune

Equivaut à :
docker rmi $(docker images --filter "dangling=true" -q)
 

Supprimer toutes les images taguées et non-taguées (dangling) ainsi que les images intermédiaires :

docker image rm -f $(docker image ls -q)

Equivaut à :
docker rmi -f $(docker image ls -q)
 

DOCKER IMAGE SAVE

Commande : docker image save
Usage:	docker image save [OPTIONS] IMAGE [IMAGE...]

Save one or more images to a tar archive (streamed to STDOUT by default)

Options:
  -o, --output string   Write to a file, instead of STDOUT

 

Sauvegarder une image existante dans une archive tar :

docker image save image[:tag] -o archive.tar

ou

docker image save image[:tag] > archive.tar

Equivaut à :
docker save image[:tag] -o archive.tar
ou
docker save image[:tag] > archive.tar
ex :

$ docker image save pong:2.0 -o pong-2.0.tar
$ tar tvf pong-2.0.tar
drwxr-xr-x 0/0               0 2018-10-16 13:22 7d689be2a587c46ff75fe9c0d4058f861444b938460f9f0729fec42dfcdffcd9/
-rw-r--r-- 0/0               3 2018-10-16 13:22 7d689be2a587c46ff75fe9c0d4058f861444b938460f9f0729fec42dfcdffcd9/VERSION
-rw-r--r-- 0/0            1410 2018-10-16 13:22 7d689be2a587c46ff75fe9c0d4058f861444b938460f9f0729fec42dfcdffcd9/json
-rw-r--r-- 0/0            4608 2018-10-16 13:22 7d689be2a587c46ff75fe9c0d4058f861444b938460f9f0729fec42dfcdffcd9/layer.tar
drwxr-xr-x 0/0               0 2018-10-16 13:22 8d153eee9afdd125f452c3e8ea10560a2653a228bc0a7ca4ec856217a50bd5f1/
-rw-r--r-- 0/0               3 2018-10-16 13:22 8d153eee9afdd125f452c3e8ea10560a2653a228bc0a7ca4ec856217a50bd5f1/VERSION
-rw-r--r-- 0/0             482 2018-10-16 13:22 8d153eee9afdd125f452c3e8ea10560a2653a228bc0a7ca4ec856217a50bd5f1/json
-rw-r--r-- 0/0        46928896 2018-10-16 13:22 8d153eee9afdd125f452c3e8ea10560a2653a228bc0a7ca4ec856217a50bd5f1/layer.tar
drwxr-xr-x 0/0               0 2018-10-16 13:22 9855d8e74b5b72748d7841326b8d9741e74523ed46e9ab9a0a8114ffdd579530/
-rw-r--r-- 0/0               3 2018-10-16 13:22 9855d8e74b5b72748d7841326b8d9741e74523ed46e9ab9a0a8114ffdd579530/VERSION
-rw-r--r-- 0/0             482 2018-10-16 13:22 9855d8e74b5b72748d7841326b8d9741e74523ed46e9ab9a0a8114ffdd579530/json
-rw-r--r-- 0/0            2560 2018-10-16 13:22 9855d8e74b5b72748d7841326b8d9741e74523ed46e9ab9a0a8114ffdd579530/layer.tar
drwxr-xr-x 0/0               0 2018-10-16 13:22 cda0fc2f1fa4a75c7ee707f4be247f082923a17ca85dd70f514772079a644f53/
-rw-r--r-- 0/0               3 2018-10-16 13:22 cda0fc2f1fa4a75c7ee707f4be247f082923a17ca85dd70f514772079a644f53/VERSION
-rw-r--r-- 0/0             482 2018-10-16 13:22 cda0fc2f1fa4a75c7ee707f4be247f082923a17ca85dd70f514772079a644f53/json
-rw-r--r-- 0/0         5345792 2018-10-16 13:22 cda0fc2f1fa4a75c7ee707f4be247f082923a17ca85dd70f514772079a644f53/layer.tar
-rw-r--r-- 0/0            4329 2018-10-16 13:22 f501db54c90de1e4cdb9c82f32069fd982f2a8e4f019910371b5a7fc085376ad.json
drwxr-xr-x 0/0               0 2018-10-16 13:22 f89d14af1325a2529c3bb2c704b62f2f2d93a9fb6bb0286ce9defcf5d65028e6/
-rw-r--r-- 0/0               3 2018-10-16 13:22 f89d14af1325a2529c3bb2c704b62f2f2d93a9fb6bb0286ce9defcf5d65028e6/VERSION
-rw-r--r-- 0/0             406 2018-10-16 13:22 f89d14af1325a2529c3bb2c704b62f2f2d93a9fb6bb0286ce9defcf5d65028e6/json
-rw-r--r-- 0/0         5053952 2018-10-16 13:22 f89d14af1325a2529c3bb2c704b62f2f2d93a9fb6bb0286ce9defcf5d65028e6/layer.tar
-rw-r--r-- 0/0             505 1970-01-01 01:00 manifest.json
-rw-r--r-- 0/0              84 1970-01-01 01:00 repositories

 

DOCKER IMAGE TAG

Commande : docker image tag
Usage:	docker image tag SOURCE_IMAGE[:TAG] TARGET_IMAGE[:TAG]

Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE

 

Créer une image taguée référençant une image existante :

docker image tag source[:tag] destination[:tag]

Equivaut à :
docker tag source[:tag] destination[:tag]
ex :

$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
ubuntu              latest              113a43faa138        3 weeks ago         81.2MB
$ docker tag ubuntu:latest darwinos/repotest:ubuntu-18.04
$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
darwinos/repotest   ubuntu-18.04        113a43faa138        3 weeks ago         81.2MB
ubuntu              latest              113a43faa138        3 weeks ago         81.2MB
$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
                            6d3b578baf20        23 seconds ago      1.16MB
busybox             latest              e1ddd7948a1c        3 weeks ago         1.16MB
$ docker image tag 6d3b578baf20 busybox:custom_V1
$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
busybox             custom_V1           6d3b578baf20        57 seconds ago      1.16MB
busybox             latest              e1ddd7948a1c        3 weeks ago         1.16MB

 

DOCKER INFO

Commande : docker info
Usage:	docker info [OPTIONS]

Display system-wide information

Options:
  -f, --format string   Format the output using the given Go template

 

Afficher les informations systèmes :

docker info

Equivaut à :
docker system info
ex :

$ docker info
Containers: 4
 Running: 2
 Paused: 0
 Stopped: 2
Images: 7
Server Version: 18.03.1-ce
Storage Driver: overlay2
 Backing Filesystem: extfs
 Supports d_type: true
 Native Overlay Diff: true
Logging Driver: json-file
Cgroup Driver: cgroupfs
Plugins:
 Volume: local
 Network: bridge host macvlan null overlay
 Log: awslogs fluentd gcplogs gelf journald json-file logentries splunk syslog
Swarm: inactive
[...]

 

DOCKER LOGIN

Commande : docker login
Usage:	docker login [OPTIONS] [SERVER]

Log in to a Docker registry

Options:
  -p, --password string   Password
      --password-stdin    Take the password from stdin
  -u, --username string   Username

 

Se loguer au Docker Registry (avec un compte valide) :

docker login [--username=username] [--password=password] 

Après connexion validée, une clé d’authentification est ajoutée dans le fichier ~/.docker/config.json.
Si déconnexion (avec docker logout), cette clé d’authentification est supprimée.
ex :

$ docker login --username=darwinos --password=P455ssw0rd
WARNING! Using --password via the CLI is insecure. Use --password-stdin.
Login Succeeded
$ docker login --username=darwinos
Password: 
Login Succeeded
$ docker login
Login with your Docker ID to push and pull images from Docker Hub. If you don't have a Docker ID, head over to https://hub.docker.com to create one.
Username: darwinos
Password: 
Login Succeeded

 

Se loguer au Docker Registry en utilisant un fichier de référence contenant le mot de passe :

cat filename | docker login --username=username --password-stdin 

ou

docker login --username=username --password-stdin < filename

ex :
Si le fichier password.txt contient le mot de passe d’authentification à Docker Hub :

P455w0rd
$ cat password.txt | docker login --username=darwinos --password-stdin
Login Succeeded

 

DOCKER LOGOUT

Commande : docker logout
Usage:	docker logout [SERVER]

Log out from a Docker registry

 

Se déloguer du Docker Registry :

docker logout

Après connexion validée, une clé d’authentification est ajoutée dans le fichier ~/.docker/config.json.
Si déconnexion (avec docker logout), cette clé d’authentification est supprimée.
ex :

$ docker logout
Removing login credentials for https://index.docker.io/v1/

 

DOCKER NETWORK

Commande : docker network
Usage:	docker network COMMAND

Manage networks

Commands:
  connect     Connect a container to a network
  create      Create a network
  disconnect  Disconnect a container from a network
  inspect     Display detailed information on one or more networks
  ls          List networks
  prune       Remove all unused networks
  rm          Remove one or more networks

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

 

DOCKER NETWORK CONNECT

Commande : docker network connect
Usage:	docker network connect [OPTIONS] NETWORK CONTAINER

Connect a container to a network

Options:
      --alias strings           Add network-scoped alias for the container
      --ip string               IPv4 address (e.g., 172.30.100.104)
      --ip6 string              IPv6 address (e.g., 2001:db8::33)
      --link list               Add link to another container
      --link-local-ip strings   Add a link-local address for the container

 

Connecter un container à un réseau existant :

docker network connect [OPTIONS] network container

ex :

$ docker container exec my_nginx ping new_nginx
ping: bad address 'new_nginx'
$ docker network connect mynet my_nginx
$ docker network connect mynet new_nginx
$ docker container exec my_nginx ping new_nginx
PING new_nginx (172.18.0.3): 56 data bytes
64 bytes from 172.18.0.3: seq=0 ttl=64 time=0.084 ms
64 bytes from 172.18.0.3: seq=1 ttl=64 time=0.377 ms
^C
$ docker container exec new_nginx ping my_nginx
PING my_nginx (172.18.0.2): 56 data bytes
64 bytes from 172.18.0.2: seq=0 ttl=64 time=0.076 ms
64 bytes from 172.18.0.2: seq=1 ttl=64 time=0.263 ms
^C

 

DOCKER NETWORK CREATE

Commande : docker network create
Usage:	docker network create [OPTIONS] NETWORK

Create a network

Options:
      --attachable           Enable manual container attachment
      --aux-address map      Auxiliary IPv4 or IPv6 addresses used by Network driver (default map[])
      --config-from string   The network from which copying the configuration
      --config-only          Create a configuration only network
  -d, --driver string        Driver to manage the Network (default "bridge")
      --gateway strings      IPv4 or IPv6 Gateway for the master subnet
      --ingress              Create swarm routing-mesh network
      --internal             Restrict external access to the network
      --ip-range strings     Allocate container ip from a sub-range
      --ipam-driver string   IP Address Management Driver (default "default")
      --ipam-opt map         Set IPAM driver specific options (default map[])
      --ipv6                 Enable IPv6 networking
      --label list           Set metadata on a network
  -o, --opt map              Set driver specific options (default map[])
      --scope string         Control the network's scope
      --subnet strings       Subnet in CIDR format that represents a network segment

 

Créer un réseau custom :

Par défaut, le réseau créé sera de type bridge.

docker network create [OPTIONS] NETWORK

Les containers attachés à un "user defined" bridge peuvent communiquer entre eux par leur nom via le serveur DNS du démon Docker, contrairement au bridge par défaut. Toutefois, les containers peuvent communiquer entre eux uniquement s’ils sont sur la même machine hôte.
ex :

$ docker network create mynet
8ab0d62fb2a33247a8a39e55da52f17d7d3d41fb1fc2dd3fbe73f4b9e506c71d

Création d’un réseau de type overlay, permettant la communication entre containers situés sur des hôtes différents (dans le cadre d’un cluster swarm) :

$ docker network create --driver overlay ovnet
4m3cgtz2xuww5m20u9pecs7o7

Idem mais avec des communications cryptées sur le réseau overlay :

$ docker network create --driver overlay --opt encrypted  ovent
4m3cgtz2xuww5m20u9pecs7o7

Création d’un réseau de type macvlan, permettant l’accès direct à une interface de la machine hôte (ne requiert pas de bridge, plus performant et léger) :

$ docker network create --driver macvlan --subnet 192.168.0.0/24 --gateway 192.168.0.1 -o parent=eth0 mvnet
17c7e6322e6b841af6184e05c9f06b3ae2496371c64f595a44f70142056f1425

 

DOCKER NETWORK DISCONNECT

Commande : docker network disconnect
Usage:	docker network disconnect [OPTIONS] NETWORK CONTAINER

Disconnect a container from a network

Options:
  -f, --force   Force the container to disconnect from a network

 

Déconnecter un container d’un réseau auquel il est attaché :

docker network disconnect [OPTIONS] network container

ex :

$ docker network disconnect mynet my_nginx
$ docker network disconnect mynet new_nginx
$ docker container exec new_nginx ping my_nginx
ping: bad address 'my_nginx'
$ docker container exec my_nginx ping new_nginx
ping: bad address 'new_nginx'

 

DOCKER NETWORK INSPECT

Commande : docker network inspect
Usage:	docker network inspect [OPTIONS] NETWORK [NETWORK...]

Display detailed information on one or more networks

Options:
  -f, --format string   Format the output using the given Go template
  -v, --verbose         Verbose output for diagnostics

 

Inspecter les informations relatives à un réseau :

docker network inspect network

ex :

$ docker network inspect bridge
[
    {
        "Name": "bridge",
        "Id": "67484527d405948d38de59e76420caff783b30a474f1a4fb6943796386144252",
        "Created": "2018-07-05T09:03:03.882456782+02:00",
        "Scope": "local",
        "Driver": "bridge",
        "EnableIPv6": false,
        "IPAM": {
            "Driver": "default",
            "Options": null,
            "Config": [
                {
                    "Subnet": "172.17.0.0/16",
                    "Gateway": "172.17.0.1"
                }
            ]
        },
        "Internal": false,
        "Attachable": false,
        "Ingress": false,
        "ConfigFrom": {
            "Network": ""
        },
        "ConfigOnly": false,
        "Containers": {},
        "Options": {
            "com.docker.network.bridge.default_bridge": "true",
            "com.docker.network.bridge.enable_icc": "true",
            "com.docker.network.bridge.enable_ip_masquerade": "true",
            "com.docker.network.bridge.host_binding_ipv4": "0.0.0.0",
            "com.docker.network.bridge.name": "docker0",
            "com.docker.network.driver.mtu": "1500"
        },
        "Labels": {}
    }
]

 

DOCKER NETWORK LS

Commande : docker network ls
Usage:	docker network ls [OPTIONS]

List networks

Aliases:
  ls, list

Options:
  -f, --filter filter   Provide filter values (e.g. 'driver=bridge')
      --format string   Pretty-print networks using a Go template
      --no-trunc        Do not truncate the output
  -q, --quiet           Only display network IDs

 

Lister les réseaux disponibles :

docker network ls

ex :

$ docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
67484527d405        bridge              bridge              local
ceb00d6eadf2        host                host                local
b50cda144567        none                null                local

 

DOCKER NETWORK PRUNE

Commande : docker network prune

 

Supprimer tous les réseaux custom inutilisés :

docker network prune

Equivaut à :
docker network rm $(docker network ls -q --filter type=custom)
 

DOCKER NETWORK RM

Commande : docker network rm
Usage:	docker network rm NETWORK [NETWORK...]

Remove one or more networks

Aliases:
  rm, remove

 

Supprimer un réseau spécifié :

docker network rm network [network...]

ex :

$ docker network rm mynet
mynet

 

DOCKER SEARCH

Commande : docker search
Usage:	docker search [OPTIONS] TERM

Search the Docker Hub for images

Options:
  -f, --filter filter   Filter output based on conditions provided
      --format string   Pretty-print search using a Go template
      --limit int       Max number of search results (default 25)
      --no-trunc        Don't truncate output

 

Faire une recherche parmi les images du Docker Hub :

docker search image [filter={stars=N | is-official={true | false} | is-automated={true | false}]

ex :

$ docker search ubuntu
NAME                                                      DESCRIPTION                                     STARS               OFFICIAL            AUTOMATED
ubuntu                                                    Ubuntu is a Debian-based Linux operating sys…   7894                [OK]                
dorowu/ubuntu-desktop-lxde-vnc                            Ubuntu with openssh-server and NoVNC            193                                     [OK]
rastasheep/ubuntu-sshd                                    Dockerized SSH service, built on top of offi…   156                                     [OK]
ansible/ubuntu14.04-ansible                               Ubuntu 14.04 LTS with ansible                   93                                      [OK]
ubuntu-upstart                                            Upstart is an event-based replacement for th…   87                  [OK]                
neurodebian                                               NeuroDebian provides neuroscience research s…   50                  [OK]                
ubuntu-debootstrap                                        debootstrap --variant=minbase --components=m…   38                  [OK]                
1and1internet/ubuntu-16-nginx-php-phpmyadmin-mysql-5      ubuntu-16-nginx-php-phpmyadmin-mysql-5          36                                      [OK]
[...]
$ docker search ubuntu --filter=stars=100
NAME                             DESCRIPTION                                     STARS               OFFICIAL            AUTOMATED
ubuntu                           Ubuntu is a Debian-based Linux operating sys…   7894                [OK]                
dorowu/ubuntu-desktop-lxde-vnc   Ubuntu with openssh-server and NoVNC            193                                     [OK]
rastasheep/ubuntu-sshd           Dockerized SSH service, built on top of offi…   156                                     [OK]
docker search ubuntu --filter=is-official=true
NAME                 DESCRIPTION                                     STARS               OFFICIAL            AUTOMATED
ubuntu               Ubuntu is a Debian-based Linux operating sys…   7894                [OK]                
ubuntu-upstart       Upstart is an event-based replacement for th…   87                  [OK]                
neurodebian          NeuroDebian provides neuroscience research s…   50                  [OK]                
ubuntu-debootstrap   debootstrap --variant=minbase --components=m…   38                  [OK]

 

DOCKER SYSTEM

Commande : docker system
Usage:	docker system COMMAND

Manage Docker

Commands:
  df          Show docker disk usage
  events      Get real time events from the server
  info        Display system-wide information
  prune       Remove unused data

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

 
Les images dangling : ancienne image taguée, ou construite (build) sans tag, ne référençant aucune image, ou layer obsolète pullé et remplacé par une version plus récente.
Les images intermédiaires : images parentes utilisées pour la construction d’une image fille, mise en cache pour un gain de performance. Seules les images intermédiaires ne peuvent pas être supprimées car ce sont des images parentes d’autres images. En supprimant les images filles, taguées ou non, les images intermédiaires utilisées pour leur construction sont supprimées également.
 

DOCKER SYSTEM DF

Commande : docker system df
Usage:	docker system df [OPTIONS]

Show docker disk usage

Options:
      --format string   Pretty-print images using a Go template
  -v, --verbose         Show detailed information on space usage

 

Afficher l’espace utilisé par les ressources Docker

docker system df

ex :

$ docker system df
TYPE                TOTAL               ACTIVE              SIZE                RECLAIMABLE
Images              9                   5                   2.149GB             1.776GB (82%)
Containers          5                   5                   1.435MB             0B (0%)
Local Volumes       2                   2                   37.16MB             0B (0%)
Build Cache         0                   0                   0B                  0B

 

DOCKER SYSTEM PRUNE

Commande : docker system prune
Usage:	docker system prune [OPTIONS]

Remove unused data

Options:
  -a, --all             Remove all unused images not just dangling ones
      --filter filter   Provide filter values (e.g. 'label==')
  -f, --force           Do not prompt for confirmation
      --volumes         Prune volumes

 

Ménage des containers : mode préservation

Les images taguées (téléchargées ou construites) seront préservées, même si elles ne sont utilisées par aucun container actif.

docker system prune

ex :

$ docker system prune
WARNING! This will remove:
        - all stopped containers
        - all networks not used by at least one container
        - all dangling images
        - all build cache

Cette commande supprimera :

  • Tous les containers arrêtés (état « Exited »)
  • Tous les réseaux, sauf ceux utilisés par au moins un container ou swarm actif
  • Toutes les images non-taguées (images dangling <none>:<none> visibles avec la commande docker images)
  • Les images intermédiaires parentes (build cache) liées aux images non-taguées filles supprimées ci-dessus

Equivaut à :

$ docker rm $(docker ps -q --filter status=exited)
$ docker network prune
$ docker rmi $(docker images --filter "dangling=true" -q)

 

Ménage des containers : mode destructeur

Les images taguées (téléchargées ou construites) seront supprimées, sauf les images utilisées par un container actif.

docker system prune --all

ex :

$ docker system prune --all
WARNING! This will remove:
        - all stopped containers
        - all networks not used by at least one container
        - all images without at least one container associated to them
        - all build cache

Cette commande supprimera :

  • Tous les containers arrêtés (état « Exited »)
  • Tous les réseaux, sauf ceux utilisés par au moins un container ou swarm actif
  • Toutes les images non-taguées (images dangling <none>:<none> visibles avec la commande docker images)
  • Les images intermédiaires parentes (build cache) liées aux images non-taguées filles supprimées ci-dessus
  • Toutes les images taguées ne référençant aucun container actif
  • Toutes les images intermédiaires parentes (build cache) liées aux images taguées filles supprimées ci-dessus

Equivaut à :

$ docker rm $(docker ps -q --filter status=exited)
$ docker network prune
$ docker rmi $(docker images --filter "dangling=true" -q)
$ docker rmi $(docker images -aq)

 

Ménage des containers : mode destructeur avancé

Les images taguées (téléchargées ou construites) seront supprimées, sauf les images utilisées par un container actif.
Les volumes seront supprimés, sauf s’ils sont utilisés par un container actif.

docker system prune --all --volumes

ex :

$ docker system prune --all --volumes
WARNING! This will remove:
        - all stopped containers
        - all networks not used by at least one container
        - all volumes not used by at least one container
        - all images without at least one container associated to them
        - all build cache

Cette commande supprimera :

  • Tous les containers arrêtés (état « Exited »)
  • Tous les réseaux, sauf ceux utilisés par au moins un container ou swarm actif
  • Toutes les images non-taguées (images dangling <none>:<none> visibles avec la commande docker images)
  • Les images intermédiaires parentes (build cache) liées aux images non-taguées filles supprimées ci-dessus
  • Toutes les images taguées ne référençant aucun container actif
  • Toutes les images intermédiaires parentes (build cache) liées aux images taguées filles supprimées ci-dessus
  • Tous les volumes sauf s’ils sont utilisés par un container actif

Equivaut à :

$ docker rm $(docker ps -q --filter status=exited)
$ docker network prune
$ docker rmi $(docker images --filter "dangling=true" -q)
$ docker rmi $(docker images -aq)
$ docker volume rm $(docker volume ls -q)

 

Ménage des containers : mode destructeur avancé complet

Supprimera tout : containers actifs et inactifs, images taguées actives ou inactives, images non taguées (dangling) actives ou inactives, images intermédiaires (build cache), volumes actifs ou inactifs,

$ docker rm -f $(docker ps -aq)
$ docker rmi -f $(docker images -q)
$ docker volume rm -f $(docker volume ls -q)
$ docker network prune

 

DOCKER VERSION

Commande : docker version
Usage:	docker version [OPTIONS]

Show the Docker version information

Options:
  -f, --format string       Format the output using the given Go template
      --kubeconfig string   Kubernetes config file

 

Afficher les versions et informations du client docker et du démon :

docker version

ex :

$ docker version
Client:
 Version:      18.03.1-ce
 API version:  1.37
 Go version:   go1.9.5
 Git commit:   9ee9f40
 Built:        Thu Apr 26 07:17:14 2018
 OS/Arch:      linux/amd64
 Experimental: false
 Orchestrator: swarm

Server:
 Engine:
  Version:      18.03.1-ce
  API version:  1.37 (minimum version 1.12)
  Go version:   go1.9.5
  Git commit:   9ee9f40
  Built:        Thu Apr 26 07:15:24 2018
  OS/Arch:      linux/amd64
  Experimental: false

 

DOCKER VOLUME

Commande : docker volume
Usage:	docker volume COMMAND

Manage volumes

Commands:
  create      Create a volume
  inspect     Display detailed information on one or more volumes
  ls          List volumes
  prune       Remove all unused local volumes
  rm          Remove one or more volumes

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

 

DOCKER VOLUME CREATE

Commande : docker volume create
Usage:	docker volume create [OPTIONS] [VOLUME]

Create a volume

Options:
  -d, --driver string   Specify volume driver name (default "local")
      --label list      Set metadata for a volume
  -o, --opt map         Set driver specific options (default map[])

 

Créer un volume de type volume :

docker volume create volume

ou

docker volume create --name volume

ex :

$ docker volume create html
html
$ docker volume ls
DRIVER              VOLUME NAME
local               html
$ docker volume inspect html
[
    {
        "CreatedAt": "2018-10-17T00:32:22+02:00",
        "Driver": "local",
        "Labels": {},
        "Mountpoint": "/var/lib/docker/volumes/html/_data",
        "Name": "html",
        "Options": {},
        "Scope": "local"
    }
]
$ sudo tree /var/lib/docker/volumes/
/var/lib/docker/volumes/
├── html
│   └── _data
└── metadata.db

2 directories, 1 file
$ docker volume create --driver local --opt type=tmpfs --opt o=size=100m logs
logs
$ docker volume inspect logs
[
    {
        "CreatedAt": "2018-10-17T03:30:15+02:00",
        "Driver": "local",
        "Labels": {},
        "Mountpoint": "/var/lib/docker/volumes/logs/_data",
        "Name": "logs",
        "Options": {
            "o": "size=100m",
            "type": "tmpfs"
        },
        "Scope": "local"
    }
]

 

DOCKER VOLUME INSPECT

Commande : docker volume inspect
Usage:	docker volume inspect [OPTIONS] VOLUME [VOLUME...]

Display detailed information on one or more volumes

Options:
  -f, --format string   Format the output using the given Go template

 

Afficher les informations relatives à un volume :

docker volume inspect volume

 

DOCKER VOLUME LS

Commande : docker volume ls
Usage:	docker volume ls [OPTIONS]

List volumes

Aliases:
  ls, list

Options:
  -f, --filter filter   Provide filter values (e.g. 'dangling=true')
      --format string   Pretty-print volumes using a Go template
  -q, --quiet           Only display volume names

 

Lister les volumes disponibles :

docker volume ls

 

DOCKER VOLUME RM

Commande : docker volume rm
Usage:	docker volume rm [OPTIONS] VOLUME [VOLUME...]

Remove one or more volumes

Aliases:
  rm, remove

Options:
  -f, --force   Force the removal of one or more volumes

 

Supprimer un volume spécifique n’étant utilisé par aucun container actif:

docker volume rm volume

 

REFERENCES

Fermer le menu
%d blogueurs aiment cette page :