Avant de commencer l’introduction aux commandes de base, nous allons créer trois (3) conteneurs.
Action – Exécuter les commandes suivantes:
$ docker run hello-world $ docker run alpine $ docker run -it -d alpine # Attention, -it et -d sont des paramètres de 'run', ils ne peuvent pas être placés ailleurs dans l'expression.
Note: ‘alpine’ est une image populaire servant de base à une image personnalisée en raison de sa très petite taille.
1.0 – Accès à l’aide intégrée: docker –help
$ docker --help Usage: docker [OPTIONS] COMMAND A self-sufficient runtime for containers Options: --config string Location of client config files (default "/Users/alain/.docker") -c, --context string Name of the context to use to connect to the daemon (overrides DOCKER_HOST env var and default context set with "docker context use") -D, --debug Enable debug mode -H, --host list Daemon socket(s) to connect to -l, --log-level string Set the logging level ("debug"|"info"|"warn"|"error"|"fatal") (default "info") --tls Use TLS; implied by --tlsverify --tlscacert string Trust certs signed only by this CA (default "/Users/alain/.docker/ca.pem") --tlscert string Path to TLS certificate file (default "/Users/alain/.docker/cert.pem") --tlskey string Path to TLS key file (default "/Users/alain/.docker/key.pem") --tlsverify Use TLS and verify the remote -v, --version Print version information and quit Management Commands: app* Docker App (Docker Inc., v0.9.1-beta3) builder Manage builds buildx* Build with BuildKit (Docker Inc., v0.4.2-docker) config Manage Docker configs container Manage containers context Manage contexts image Manage images manifest Manage Docker image manifests and manifest lists network Manage networks node Manage Swarm nodes plugin Manage plugins scan* Docker Scan (Docker Inc., v0.5.0) secret Manage Docker secrets service Manage services stack Manage Docker stacks swarm Manage Swarm system Manage Docker trust Manage trust on Docker images volume Manage volumes Commands: attach Attach local standard input, output, and error streams to a running container build Build an image from a Dockerfile commit Create a new image from a container's changes cp Copy files/folders between a container and the local filesystem create Create a new container diff Inspect changes to files or directories on a container's filesystem events Get real time events from the server exec Run a command in a running container export Export a container's filesystem as a tar archive history Show the history of an image images List images import Import the contents from a tarball to create a filesystem image info Display system-wide information inspect Return low-level information on Docker objects kill Kill one or more running containers load Load an image from a tar archive or STDIN login Log in to a Docker registry logout Log out from a Docker registry logs Fetch the logs of a container pause Pause all processes within one or more containers port List port mappings or a specific mapping for the container ps List containers pull Pull an image or a repository from a registry push Push an image or a repository to a registry rename Rename a container restart Restart one or more containers rm Remove one or more containers rmi Remove one or more images run Run a command in a new container save Save one or more images to a tar archive (streamed to STDOUT by default) search Search the Docker Hub for images start Start one or more stopped containers stats Display a live stream of container(s) resource usage statistics stop Stop one or more running containers tag Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE top Display the running processes of a container unpause Unpause all processes within one or more containers update Update configuration of one or more containers version Show the Docker version information wait Block until one or more containers stop, then print their exit codes Run 'docker COMMAND --help' for more information on a command. To get more help with docker, check out guides at https://docs.docker.com/go/guides/
Note: Sous Linux, si vous obtenez un message de permission refusée alors:
# Exemple d'erreur: $ docker run hello-world docker: Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Post http://%2Fvar%2Frun%2Fdocker.sock/v1.40/containers/create: dial unix /var/run/docker.sock: connect: permission denied. See 'docker run --help'. --- Solution: sudo groupadd docker sudo usermod -aG docker $USER sudo chmod 666 /var/run/docker.sock
1.1 – Aide sur une commande: docker ‘cmd’ –help
docker ps --help Usage: docker ps [OPTIONS] List containers 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 container IDs -s, --size Display total file sizes
Action – Afficher l’aide de la commande ‘run’
Question – À quoi servent les options -i -t et -d?
PROBLÈME avec la console interactive (-it) sous git-bash:
https://willi.am/blog/2016/08/08/docker-for-windows-interactive-sessions-in-mintty-git-bash/ Solution: $ winpty docker exec -it alpine sh
2.0 – Docker Engine propose deux types de commandes,
Par exemple;
# 1 - Lister les conteneurs via la commande de gestion 'container' # docker container 'CMD' $ docker container ls # 2 - Lister les conteneurs avec une commande directe $ docker ps
2.1 – Obtenir l’aide d’une commande de gestion: docker cmdGestion –help
$ docker container --help Usage: docker container COMMAND Manage containers 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.
2.2 – Obtenir la liste des images locales: docker images
$ docker images REPOSITORY TAG IMAGE ID CREATED SIZE alpine latest 7731472c3f2a 10 days ago 5.61MB hello-world latest bf756fb1ae65 12 months ago 13.3kB
2.3 – Obtenir la liste des conteneurs en exécution: docker ps
$ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES c8026675b9b7 alpine "/bin/sh" 48 minutes ago Up 48 minutes intelligent_noether
2.4 – Obtenir la liste de tous les conteneurs – incluant ceux qui sont terminés: ps -a
$ docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES c8026675b9b7 alpine "/bin/sh" 49 minutes ago Up 49 minutes intelligent_noether b321afb1ea0f alpine "-it -d" 49 minutes ago Created practical_lamarr 1114bbe1af61 alpine "/bin/sh" 49 minutes ago Exited (0) 49 minutes ago dazzling_zhukovsky d09c5b00adca hello-world "/hello" 50 minutes ago Exited (0) 50 minutes ago charming_mcnulty
2.4.1 – Rechercher des images disponibles sur ‘docker hub’: docker search ‘expression’
$ docker search cowsay NAME DESCRIPTION STARS OFFICIAL AUTOMATED lherrera/cowsay 4 grycap/cowsay Alpine-less Cowsay (with Fortune) 2 [OK] mwendler/cowsay a cowsay setup 1 [OK] jtcressy/cowsay Cowsay, Dockerized. 1 [OK] mattaudesse/cowsay Dockerized cowsay via Alpine Linux 1 ...
2.4.2 – Obtenir une image à partir d’un dépôt: docker pull éditeur/image
$ docker pull lherrera/cowsay Using default tag: latest latest: Pulling from lherrera/cowsay 5c90d4a2d1a8: Pull complete 616b53547af8: Pull complete e5f927ff4e43: Pull complete Digest: sha256:ce709bc4dfb0c5c5c9d3e779babdcc289a7d0dbacd583d08b3bb05d017f1f593 Status: Downloaded newer image for lherrera/cowsay:latest docker.io/lherrera/cowsay:latest # Afficher les images locales $ docker images REPOSITORY TAG IMAGE ID CREATED SIZE alpine latest 7731472c3f2a 10 days ago 5.61MB hello-world latest bf756fb1ae65 12 months ago 13.3kB lherrera/cowsay latest 47e12946765b 4 years ago 186MB
Note: Lorsque nous téléchargeons une image, nous obtenons toujours la dernière version. Par exemple, ‘alpine:latest’. Nous verrons plus tard comment préciser une autre version.
2.4.3 – Démarrer un conteneur (instance d’image): docker run ID
docker run 47e12946765b ________________________________________ / No group of professionals meets except \ | to conspire against the public at | | large. | | | \ -- Mark Twain / ---------------------------------------- \ ^__^ \ (oo)\_______ (__)\ )\/\ ||----w | || ||
2.4.4 – Effacer un conteneur: docker rm ID
# 1 - Identifier le conteneur $ docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES a27294467a25 47e12946765b "/entrypoint.sh" About a minute ago Exited (0) About a minute ago elegant_gauss # 2 - Effacer le conteneur $ docker rm a27294467a25
2.4.5 – Effacer une image: docker rmi ID
# 1 - Obtenir l'image ID $ docker images docker images REPOSITORY TAG IMAGE ID CREATED SIZE alpine latest 7731472c3f2a 10 days ago 5.61MB hello-world latest bf756fb1ae65 12 months ago 13.3kB lherrera/cowsay latest 47e12946765b 4 years ago 186MB # 2 - Effacer l'image $ docker rmi 47e12946765b Untagged: lherrera/cowsay:latest Untagged: lherrera/cowsay@sha256:ce709bc4dfb0c5c5c9d3e779babdcc289a7d0dbacd583d08b3bb05d017f1f593 Deleted: sha256:47e12946765b355fb29cdd14f54e78a05d24cb5d68afc1e0e92cd4a0243a1b1a Deleted: sha256:b7711ab7662ee24f1a48c831811b99e623b4d44b664c766d1570a8db6ddc481e Deleted: sha256:35767520ef4a2e79c4c6fd68b48fd61ef8dc9c95900e88eeff4c901746bb72ee Deleted: sha256:42755cf4ee95900a105b4e33452e787026ecdefffcc1992f961aa286dc3f7f95
Note: S’il existe des instances ‘conteneurs’ de cette image, il faudra effacer les conteneurs avant ou bien utiliser l’option -f pour forcer la suppression de l’image.
2.5 – Redémarrer un conteneur: docker restart
# Voici un conteneur terminé: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES d09c5b00adca hello-world "/hello" 50 minutes ago Exited (0) 50 minutes ago charming_mcnulty # Il peut-être redémarré à partir de son ID ou de son nom $ docker restart d09c5b00adca $ docker restart charming_mcnulty
2.6 – Démarrer un conteneur en mode terminal (-t) interactif (-i): docker run -it image
$ docker run -it alpine / # ls bin dev etc home lib media mnt opt proc root run sbin srv sys tmp usr var / #
Note: la commande ‘exit’ va quitter et terminer le conteneur.
/ # exit alain@MacBook-Pro-de-Alain 420-4D4 % docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES c8026675b9b7 alpine "/bin/sh" About an hour ago Up About an hour intelligent_noether alain@MacBook-Pro-de-Alain 420-4D4 % docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 348d87139a48 alpine "/bin/sh" 2 minutes ago Exited (0) 19 seconds ago elated_galileo
2.7 – S’attacher à un conteneur en cours d’exécution: docker attach ID
Au début de ce document, nous avons créé un conteneur ‘alpine’ avec les options ‘-it -d’.
Ce conteneur roule donc présentement en arrière plan.
$ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES c8026675b9b7 alpine "/bin/sh" About an hour ago Up About an hour intelligent_noether
Pour s’y connecter, il faut utiliser la commande ‘attach ID/OU_NOM’.
$ docker attach intelligent_noether / # pwd / / # mkdir 420-4C4 / # cd 420-4C4/ /420-4C4 # touch je-suis-passé-par-ici.txt /420-4C4 # ls -l total 0 -rw-r--r-- 1 root root 0 Jan 25 18:44 je-suis-passé-par-ici.txt /420-4C4 # exit $
Note: la commande ‘exit’ a provoqué l’arrête du conteneur:
$ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES $
2.8 – Redémarrer le conteneur précédent: docker restart ID
$ docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 348d87139a48 alpine "/bin/sh" 55 minutes ago Exited (0) 53 minutes ago elated_galileo --> c8026675b9b7 alpine "/bin/sh" 2 hours ago Exited (0) 3 minutes ago intelligent_noether $ docker restart c8 $ docker attach c8 / # ls -l total 60 drwxr-xr-x 2 root root 4096 Jan 25 18:44 420-4C4 drwxr-xr-x 2 root root 4096 Jan 14 11:49 bin ...
Note: Il n’est pas nécessaire de fournir tout le numéro d’ID dans une commande. Seulement un nombre suffisant de caractères pour rendre l’ID unique.
2.9 – Quitter un conteneur sans provoquer son arrêt: Séquence CTRL P+Q
# CTRL P+Q - permet de quitter sans arrêter le conteneur / # read escape sequence $ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES c8026675b9b7 alpine "/bin/sh" 2 hours ago Up 3 minutes intelligent_noether $
2.10 – Arrêter un conteneur: docker stop ID
$ docker stop c8 c8 $ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES $
2.11 – Nommer un conteneur: docker run –name
$ docker run -it -d --name monAlpine alpine ce5bde565bfa21f9b3d4f0cf8dc386cfe193c6dabbcc25a676371b51a32ec7c3 $ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES ce5bde565bfa alpine "/bin/sh" 7 seconds ago Up 6 seconds monAlpine $ docker attach monAlpine / # CTRL P+Q
Note: Attention, quitter le conteneur sans provoquer son arrêt: CTRL P+Q
2.12 – Renommer un conteneur: docker rename nom/ID nouveauNom
$ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES ce5bde565bfa alpine "/bin/sh" 7 seconds ago Up 6 seconds monAlpine $ docker rename monAlpine test $ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES ce5bde565bfa alpine "/bin/sh" 4 minutes ago Up 4 minutes test
2.13 – Effacer tous les conteneurs et toutes les images
Voici comment réinitialiser à zéro votre installation de docker:
*** DANGER CETTE COMMANDE EFFACE AUSSI LES IMAGES DE MINIKUBE ***
# -------------------------------------------------------- # Effacer tous les conteneurs et libérer l'espace disque # Cette commande efface aussi les images. docker container stop $(docker container ls -aq) && docker system prune -af --volumes # ou pour powershell: docker container stop $(docker container ls -aq) ; docker system prune -af --volumes
Plusieurs images offrent des services via le protocol TPC/IP. Par exemple, une application Web. Par défaut, le réseau du conteneur est isolé et hermétique.
Il est par contre possible d’établir un lien (BIND) entre le réseau du conteneur et l’ordinateur hôte.
Voici un exemple:
3.1 – Obtenir l’image du serveur web ngnix
$ docker search nginx NAME DESCRIPTION STARS OFFICIAL AUTOMATED nginx Official build of Nginx. 14341 [OK] jwilder/nginx-proxy Automated Nginx reverse proxy for docker con… 1947 [OK] richarvey/nginx-php-fpm Container running Nginx + PHP-FPM capable of… 802 [OK] ... $ docker pull nginx Using default tag: latest latest: Pulling from library/nginx a076a628af6f: Pull complete 0732ab25fa22: Pull complete d7f36f6fe38f: Pull complete f72584a26f32: Pull complete 7125e4df9063: Pull complete Digest: sha256:10b8cc432d56da8b61b070f4c7d2543a9ed17c2b23010b43af434fd40e2ca4aa Status: Downloaded newer image for nginx:latest docker.io/library/nginx:latest
3.2 – Créer un conteneur avec un lien sur le pour IP 80 (http): docker -p P-host:P-conteneur
# Lancer le serveur Web sur le port 8080 de l'ordinateur hôte $ docker run -it -d -p 8080:80 --name monServeurWeb nginx eb66bdef2f73caf6ed04e17f132d613a84f9fa15163b074d27fc3a93cbc4c4b3 # Afficher les conteneurs actids $ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES eb66bdef2f73 nginx "/docker-entrypoint.…" 39 seconds ago Up 38 seconds 0.0.0.0:8080->80/tcp monServeurWeb
3.3 – Vérifier le fonctionnement du serveur web: localhost:8080
3.4 – Consultation de la documentation de l’image ‘nginx’
https://hub.docker.com/_/nginx
Dans la documentation il est mentionné que le répertoire racine du site web est localisé dans :
/usr/share/nginx/html
3.5 – Nous allons modifier son contenu: docker exec
# 1 - Connexion au shell du conteneur nginx $ docker exec -it monServeurWeb /bin/bash root@eb66bdef2f73:/# cd /usr/share/nginx/html root@eb66bdef2f73:/usr/share/nginx/html# ls 50x.html index.html # 2 - Créer un nouveau document html $ echo "<center><h1>Mon serveur WEB</h1></center>" > index2.html # 3 - Tester dans le fureteur
Question: Est-ce que quitter le ‘shell’ avec ‘exit’ va terminer le conteneur?
NOTE: la commande ‘attach’ va exécuter le point d’entrée. Dans le cas de nginx, cela ne correspond pas à un ‘shell’.
3.6 – Laboratoire:
3.7 – Afficher les statistiques d’utilisation matériel des conteneurs en cours d’exécution.
$ docker container stats --------------------------------------------------------------------------- CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS eb66bdef2f73 monServeurWeb 0.00% 2.098MiB / 1.942GiB 0.11% 41.3kB / 24.1kB 65.5kB / 0B 2 CTRL+C pour quitter
3.8 – Afficher le journal (log) d’un conteneur: docker logs ID|NAME
$ docker logs monServeurWeb /docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration /docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/ /docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh 10-listen-on-ipv6-by-default.sh: info: Getting the checksum of /etc/nginx/conf.d/default.conf 10-listen-on-ipv6-by-default.sh: info: Enabled listen on IPv6 in /etc/nginx/conf.d/default.conf /docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh /docker-entrypoint.sh: Configuration complete; ready for start up 172.17.0.1 - - [25/Jan/2021:20:41:47 +0000] "GET / HTTP/1.1" 200 612 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1 Safari/605.1.15" "-" 2021/01/25 20:41:47 [error] 30#30: *1 open() "/usr/share/nginx/html/favicon.ico" failed (2: No such file or directory), client: 172.17.0.1, server: localhost, request: "GET /favicon.ico HTTP/1.1", host: "localhost:8080", referrer: "http://localhost:8080/" 172.17.0.1 - - [25/Jan/2021:20:41:47 +0000] "GET /favicon.ico HTTP/1.1" 404 ...