Version : 2022.01

Dernière mise-à-jour : 2022/12/15 16:44

DOF102 - Démarrer avec Docker

Contenu du Module

  • DOF102 - Démarrer avec Docker
    • Contenu du Module
    • Présentation de Docker
    • LAB #1 - Travailler avec Docker
      • 1.1 - Installer docker
      • 1.2 - Démarrer un Conteneur
      • 1.3 - Consulter la Liste des Conteneurs et Images
      • 1.4 - Rechercher une Image dans un Dépôt
      • 1.5 - Supprimer un Conteneur d'une Image
      • 1.6 - Créer une Image à partir d'un Conteneur Modifié
      • 1.7 - Supprimer une Image
      • 1.8 - Créer un Conteneur avec un Nom Spécifique
      • 1.9 - Exécuter une Commande dans un Conteneur
      • 1.10 - Injecter des Variables d'Environnement dans un Conteneur
      • 1.11 - Modifier le Nom d'Hôte d'un Conteneur
      • 1.12 - Mapper des Ports d'un Conteneur
      • 1.13 - Démarrer un Conteneur en mode Détaché
      • 1.14 - Accéder aux Services d'un Conteneur de l'Extérieur
      • 1.15 - Arrêter et Démarrer un Conteneur
      • 1.16 - Utiliser des Signaux avec un Conteneur
      • 1.17 - Forcer la Suppression d'un Conteneur en cours d'Exécution
      • 1.18 - Utilisation Simple d'un Volume
      • 1.19 - Télécharger une image sans créer un conteneur
      • 1.20 - S'attacher à un conteneur en cours d'exécution
      • 1.21 - Installer un logiciel dans le conteneur
      • 1.22 - Utilisation de la commande docker commit
      • 1.23 - Se connecter au serveur du conteneur de l'extérieur

Présentation de Docker

La virtualisation classique nécessite l'utilisation d'un hyperviseur :

Docker est une application de virtualisation légère qui utilise des images et des conteneurs.

Une image est un paquet exécutable contenant tout ce qu'il est nécessaire afin d'exécuter un logiciel donné, incluant :

  • le code
  • un runtime
  • des bibliothèques,
  • des variables d'environnement
  • des fichiers de configuration

Un conteneur est une instance de l'image en cours d'exécution en mémoire. Elle est isolée de l'environnement de l'hôte par défaut mais peut accéder à des fichiers et de ports de l'hôte selon la configuration.

Les conteneurs exécutent des applications nativement en utilisant le noyau de la machine hôte. De ce fait les performances d'un conteneur sont supérieures à celles d'une machine virtuelle qui doit passer par un hyperviseur pour accéder aux ressources de la machine hôte.

Docker existe en deux versions Docker-CE (Docker Community Edition) et Docker-EE (Docker Enterprise Edition). Pour consulter les différences entre les deux versions, consultez le lien https://docs.docker.com/engine/installation/.

Pour gérer le système de fichiers du conteneur, Docker utilisait au départ le filesystem AUFS. AUFS est un système de fichiers de la famille UnionFS. Un système de fichier de type UnionFS assemble des repertoires multiples les uns sur les autres pour ensuite les présenter sous forme d'un repertoire unique contenant les objets les plus récents grâce à un union mount. Les repertoires sous AUFS sont appelés des branches et se trouvent dans /var/lib/docker/aufs :

Le système de fichiers AUFS a été ensuite remplacé dans Docker par le système de fichiers OverlayFS. Ce système de fichiers combine deux répertoires appelés Layers. Le layer inférieur porte le nom lowerdir tandis que le niveau au dessus est appelé le upperdir. La vue unifiée porte le nom merged. Dans le cas où les layers de conteneur et de l'image contiennent le même objet, le conteneur “gagne” et cache l'objet dans l'image :

Image 2

Le système de fichiers OverlayFS ne sait gérer que deux niveaux. Ceci implique une utilisation excessive d'inodes dans la cas d'une image à de niveaux multiples car chaque image doit résider dans son propre repertoire qui se situe dans /var/lib/docker/overlay. Des liens physiques sont ensuite utilisés pour référencer des données dans les niveaux inférieurs.

Cette limitation a donné lieu à l'introduction du système de fichiers Overlay2 actuellement utilisé par Docker. Overlay2 est capable de gérer 128 layers.

LAB #1 - Travailler avec Docker

1.1 - Installer docker

Docker n'est pas dans le dépôts de Debian. Afin de l'installer il convient d'ajouter le dépôt de docker. Premièrement, il est nécessaire d'installer les paquets permettant à Debian d'utiliser un dépôt en https :

root@debian9:~# apt-get update
...
root@debian9:~# apt-get install apt-transport-https ca-certificates curl gnupg2 software-properties-common
Reading package lists... Done
Building dependency tree       
Reading state information... Done
ca-certificates is already the newest version.
ca-certificates set to manually installed.
gnupg2 is already the newest version.
gnupg2 set to manually installed.
The following extra packages will be installed:
  libcurl3 python3-dbus python3-software-properties unattended-upgrades
Suggested packages:
  python-dbus-doc python3-dbus-dbg
The following NEW packages will be installed:
  apt-transport-https curl libcurl3 python3-dbus python3-software-properties
  software-properties-common unattended-upgrades
0 upgraded, 7 newly installed, 0 to remove and 1 not upgraded.
Need to get 960 kB of archives.
After this operation, 2,344 kB of additional disk space will be used.
Do you want to continue? [Y/n] 

Téléchargez la clef GPG officielle de docker :

root@debian9:~# curl -fsSL https://download.docker.com/linux/debian/gpg | apt-key add -
OK

Vérifiez que l'ID de la clef est 9DC8 5822 9FC7 DD38 854A E2D8 8D81 803C 0EBF CD88 :

root@debian9:~# apt-key fingerprint 0EBFCD88
/etc/apt/trusted.gpg
--------------------
pub   4096R/0EBFCD88 2017-02-22
      Key fingerprint = 9DC8 5822 9FC7 DD38 854A  E2D8 8D81 803C 0EBF CD88
uid                  Docker Release (CE deb) <docker@docker.com>
sub   4096R/F273FCD8 2017-02-22
...

Ajoutez le dépôt stable de docker :

root@debian9:~# add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/debian $(lsb_release -cs) stable"

Important - Notez que la commande lsb_release -cs retourne le nom de la distribution Debian, à savoir dans ce cas stretch.

Installez maintenant le paquet docker-ce :

root@debian9:~# apt-get update
...
root@debian9:~# apt-get install docker-ce
Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following extra packages will be installed:
  aufs-tools cgroupfs-mount git git-man libapparmor1 liberror-perl
  libnih-dbus1 libnih1 makedev mountall plymouth rsync
Suggested packages:
  git-daemon-run git-daemon-sysvinit git-doc git-el git-email git-gui gitk
  gitweb git-arch git-cvs git-mediawiki git-svn plymouth-themes
The following NEW packages will be installed:
  aufs-tools cgroupfs-mount docker-ce git git-man libapparmor1 liberror-perl
  libnih-dbus1 libnih1 makedev mountall plymouth rsync
0 upgraded, 13 newly installed, 0 to remove and 99 not upgraded.
Need to get 26.5 MB of archives.
After this operation, 123 MB of additional disk space will be used.
Do you want to continue? [Y/n] 

Dernièrement, vérifiez la version de Docker client et serveur :

root@debian9:~# docker version
Client: Docker Engine - Community
 Version:           19.03.4
 API version:       1.40
 Go version:        go1.12.10
 Git commit:        9013bf583a
 Built:             Fri Oct 18 15:52:34 2019
 OS/Arch:           linux/amd64
 Experimental:      false

Server: Docker Engine - Community
 Engine:
  Version:          19.03.4
  API version:      1.40 (minimum version 1.12)
  Go version:       go1.12.10
  Git commit:       9013bf583a
  Built:            Fri Oct 18 15:51:05 2019
  OS/Arch:          linux/amd64
  Experimental:     false
 containerd:
  Version:          1.2.10
  GitCommit:        b34a5c8af56e510852c35414db4c1f4fa6172339
 runc:
  Version:          1.0.0-rc8+dev
  GitCommit:        3e425f80a8c931f88e6d94a8c831b9d5aa481657
 docker-init:
  Version:          0.18.0
  GitCommit:        fec3683

Docker est composé de trois éléments : un serveur, un client et un ou plusieur Repositories ou Dépôts :

1.2 - Démarrer un Conteneur

Démarrez un conteneur de l'image hello-world :

root@debian9:~# docker run hello-world
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
1b930d010525: Pull complete 
Digest: sha256:2557e3c07ed1e38f26e389462d03ed943586f744621577a99efb77324b0fe535
Status: Downloaded newer image for hello-world:latest

Hello from Docker!
This message shows that your installation appears to be working correctly.

To generate this message, Docker took the following steps:
 1. The Docker client contacted the Docker daemon.
 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
    (amd64)
 3. The Docker daemon created a new container from that image which runs the
    executable that produces the output you are currently reading.
 4. The Docker daemon streamed that output to the Docker client, which sent it
    to your terminal.

To try something more ambitious, you can run an Ubuntu container with:
 $ docker run -it ubuntu bash

Share images, automate workflows, and more with a free Docker ID:
 https://hub.docker.com/

For more examples and ideas, visit:
 https://docs.docker.com/get-started/

Important - Notez que si l'image servant à générer le conteneur n'est pas présente sur le système hôte, celle-ci est téléchargée automatiquement depuis un dépôt ( par défaut le dépôt docker.io ) en utilisant la commande docker pull.

Démarrez un conteneur de l'image ubuntu:latest en mode interactif grâce à l'utilisation des options -i et -t en lui passant en argument bash pour que celui-ci soient lancé au démarrage du conteneur :

root@debian9:~# docker run -it ubuntu bash
Unable to find image 'ubuntu:latest' locally
latest: Pulling from library/ubuntu
898c46f3b1a1: Pull complete 
63366dfa0a50: Pull complete 
041d4cd74a92: Pull complete 
6e1bee0f8701: Pull complete 
Digest: sha256:017eef0b616011647b269b5c65826e2e2ebddbe5d1f8c1e56b3599fb14fabec8
Status: Downloaded newer image for ubuntu:latest
root@3a3f9bda6cbd:/# ls
bin  boot  dev  etc  home  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
root@3a3f9bda6cbd:/# cat /etc/lsb-release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=18.04
DISTRIB_CODENAME=bionic
DISTRIB_DESCRIPTION="Ubuntu 18.04.2 LTS"

Important - Notez que dans ce cas le conteneur est lancé avec comme argument bash qui lancera /bin/bash dans le conteneur.

Consulter la liste des paquets installés dans le conteneur ubuntu :

root@835001339e79:/# dpkg -l
Desired=Unknown/Install/Remove/Purge/Hold
| Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend
|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)
||/ Name                                 Version                 Architecture            Description
+++-====================================-=======================-=======================-=============================================================================
ii  adduser                              3.116ubuntu1            all                     add and remove users and groups
ii  apt                                  1.6.8                   amd64                   commandline package manager
ii  base-files                           10.1ubuntu2.4           amd64                   Debian base system miscellaneous files
ii  base-passwd                          3.5.44                  amd64                   Debian base system master password and group files
ii  bash                                 4.4.18-2ubuntu1         amd64                   GNU Bourne Again SHell
ii  bsdutils                             1:2.31.1-0.4ubuntu3.3   amd64                   basic utilities from 4.4BSD-Lite
ii  bzip2                                1.0.6-8.1               amd64                   high-quality block-sorting file compressor - utilities
ii  coreutils                            8.28-1ubuntu1           amd64                   GNU core utilities
ii  dash                                 0.5.8-2.10              amd64                   POSIX-compliant shell
ii  debconf                              1.5.66                  all                     Debian configuration management system
ii  debianutils                          4.8.4                   amd64                   Miscellaneous utilities specific to Debian
ii  diffutils                            1:3.6-1                 amd64                   File comparison utilities
ii  dpkg                                 1.19.0.5ubuntu2.1       amd64                   Debian package management system
ii  e2fsprogs                            1.44.1-1ubuntu1.1       amd64                   ext2/ext3/ext4 file system utilities
ii  fdisk                                2.31.1-0.4ubuntu3.3     amd64                   collection of partitioning utilities
ii  findutils                            4.6.0+git+20170828-2    amd64                   utilities for finding files--find, xargs
ii  gcc-8-base:amd64                     8.2.0-1ubuntu2~18.04    amd64                   GCC, the GNU Compiler Collection (base package)
ii  gpgv                                 2.2.4-1ubuntu1.2        amd64                   GNU privacy guard - signature verification tool
ii  grep                                 3.1-2                   amd64                   GNU grep, egrep and fgrep
ii  gzip                                 1.6-5ubuntu1            amd64                   GNU compression utilities
ii  hostname                             3.20                    amd64                   utility to set/show the host name or domain name
ii  init-system-helpers                  1.51                    all                     helper tools for all init systems
ii  libacl1:amd64                        2.2.52-3build1          amd64                   Access control list shared library
ii  libapt-pkg5.0:amd64                  1.6.8                   amd64                   package management runtime library
ii  libattr1:amd64                       1:2.4.47-2build1        amd64                   Extended attribute shared library
ii  libaudit-common                      1:2.8.2-1ubuntu1        all                     Dynamic library for security auditing - common files
ii  libaudit1:amd64                      1:2.8.2-1ubuntu1        amd64                   Dynamic library for security auditing
ii  libblkid1:amd64                      2.31.1-0.4ubuntu3.3     amd64                   block device ID library
ii  libbz2-1.0:amd64                     1.0.6-8.1               amd64                   high-quality block-sorting file compressor library - runtime
ii  libc-bin                             2.27-3ubuntu1           amd64                   GNU C Library: Binaries
ii  libc6:amd64                          2.27-3ubuntu1           amd64                   GNU C Library: Shared libraries
ii  libcap-ng0:amd64                     0.7.7-3.1               amd64                   An alternate POSIX capabilities library
ii  libcom-err2:amd64                    1.44.1-1ubuntu1.1       amd64                   common error description library
ii  libdb5.3:amd64                       5.3.28-13.1ubuntu1      amd64                   Berkeley v5.3 Database Libraries [runtime]
ii  libdebconfclient0:amd64              0.213ubuntu1            amd64                   Debian Configuration Management System (C-implementation library)
ii  libext2fs2:amd64                     1.44.1-1ubuntu1.1       amd64                   ext2/ext3/ext4 file system libraries
ii  libfdisk1:amd64                      2.31.1-0.4ubuntu3.3     amd64                   fdisk partitioning library
ii  libffi6:amd64                        3.2.1-8                 amd64                   Foreign Function Interface library runtime
ii  libgcc1:amd64                        1:8.2.0-1ubuntu2~18.04  amd64                   GCC support library
ii  libgcrypt20:amd64                    1.8.1-4ubuntu1.1        amd64                   LGPL Crypto library - runtime library
ii  libgmp10:amd64                       2:6.1.2+dfsg-2          amd64                   Multiprecision arithmetic library
ii  libgnutls30:amd64                    3.5.18-1ubuntu1         amd64                   GNU TLS library - main runtime library
ii  libgpg-error0:amd64                  1.27-6                  amd64                   library for common error values and messages in GnuPG components
ii  libhogweed4:amd64                    3.4-1                   amd64                   low level cryptographic library (public-key cryptos)
ii  libidn2-0:amd64                      2.0.4-1.1build2         amd64                   Internationalized domain names (IDNA2008/TR46) library
ii  liblz4-1:amd64                       0.0~r131-2ubuntu3       amd64                   Fast LZ compression algorithm library - runtime
ii  liblzma5:amd64                       5.2.2-1.3               amd64                   XZ-format compression library
ii  libmount1:amd64                      2.31.1-0.4ubuntu3.3     amd64                   device mounting library
ii  libncurses5:amd64                    6.1-1ubuntu1.18.04      amd64                   shared libraries for terminal handling
ii  libncursesw5:amd64                   6.1-1ubuntu1.18.04      amd64                   shared libraries for terminal handling (wide character support)
ii  libnettle6:amd64                     3.4-1                   amd64                   low level cryptographic library (symmetric and one-way cryptos)
ii  libp11-kit0:amd64                    0.23.9-2                amd64                   library for loading and coordinating access to PKCS#11 modules - runtime
ii  libpam-modules:amd64                 1.1.8-3.6ubuntu2.18.04. amd64                   Pluggable Authentication Modules for PAM
ii  libpam-modules-bin                   1.1.8-3.6ubuntu2.18.04. amd64                   Pluggable Authentication Modules for PAM - helper binaries
ii  libpam-runtime                       1.1.8-3.6ubuntu2.18.04. all                     Runtime support for the PAM library
ii  libpam0g:amd64                       1.1.8-3.6ubuntu2.18.04. amd64                   Pluggable Authentication Modules library
ii  libpcre3:amd64                       2:8.39-9                amd64                   Old Perl 5 Compatible Regular Expression Library - runtime files
ii  libprocps6:amd64                     2:3.3.12-3ubuntu1.1     amd64                   library for accessing process information from /proc
ii  libseccomp2:amd64                    2.3.1-2.1ubuntu4        amd64                   high level interface to Linux seccomp filter
ii  libselinux1:amd64                    2.7-2build2             amd64                   SELinux runtime shared libraries
ii  libsemanage-common                   2.7-2build2             all                     Common files for SELinux policy management libraries
ii  libsemanage1:amd64                   2.7-2build2             amd64                   SELinux policy management library
ii  libsepol1:amd64                      2.7-1                   amd64                   SELinux library for manipulating binary security policies
ii  libsmartcols1:amd64                  2.31.1-0.4ubuntu3.3     amd64                   smart column output alignment library
ii  libss2:amd64                         1.44.1-1ubuntu1.1       amd64                   command-line interface parsing library
ii  libstdc++6:amd64                     8.2.0-1ubuntu2~18.04    amd64                   GNU Standard C++ Library v3
ii  libsystemd0:amd64                    237-3ubuntu10.13        amd64                   systemd utility library
ii  libtasn1-6:amd64                     4.13-2                  amd64                   Manage ASN.1 structures (runtime)
ii  libtinfo5:amd64                      6.1-1ubuntu1.18.04      amd64                   shared low-level terminfo library for terminal handling
ii  libudev1:amd64                       237-3ubuntu10.13        amd64                   libudev shared library
ii  libunistring2:amd64                  0.9.9-0ubuntu1          amd64                   Unicode string library for C
ii  libuuid1:amd64                       2.31.1-0.4ubuntu3.3     amd64                   Universally Unique ID library
ii  libzstd1:amd64                       1.3.3+dfsg-2ubuntu1     amd64                   fast lossless compression algorithm
ii  login                                1:4.5-1ubuntu1          amd64                   system login tools
ii  lsb-base                             9.20170808ubuntu1       all                     Linux Standard Base init script functionality
ii  mawk                                 1.3.3-17ubuntu3         amd64                   a pattern scanning and text processing language
ii  mount                                2.31.1-0.4ubuntu3.3     amd64                   tools for mounting and manipulating filesystems
ii  ncurses-base                         6.1-1ubuntu1.18.04      all                     basic terminal type definitions
ii  ncurses-bin                          6.1-1ubuntu1.18.04      amd64                   terminal-related programs and man pages
ii  passwd                               1:4.5-1ubuntu1          amd64                   change and administer password and group data
ii  perl-base                            5.26.1-6ubuntu0.3       amd64                   minimal Perl system
ii  procps                               2:3.3.12-3ubuntu1.1     amd64                   /proc file system utilities
ii  sed                                  4.4-2                   amd64                   GNU stream editor for filtering/transforming text
ii  sensible-utils                       0.0.12                  all                     Utilities for sensible alternative selection
ii  sysvinit-utils                       2.88dsf-59.10ubuntu1    amd64                   System-V-like utilities
ii  tar                                  1.29b-2ubuntu0.1        amd64                   GNU version of the tar archiving utility
ii  ubuntu-keyring                       2018.09.18.1~18.04.0    all                     GnuPG keys of the Ubuntu archive
ii  util-linux                           2.31.1-0.4ubuntu3.3     amd64                   miscellaneous system utilities
ii  zlib1g:amd64                         1:1.2.11.dfsg-0ubuntu2  amd64                   compression library - runtime
root@835001339e79:/# exit
exit
root@debian9:~# 

Les options de la commande docker run peuvent être visualisées avec la commande :

root@debian9:~# docker run --help

Usage:	docker 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: <name|uid>[:<group|gid>])
      --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

1.3 - Consulter la Liste des Conteneurs et Images

Pour consulter tous les conteneurs, utilisez la commande docker ps avec l'option -a :

root@debian9:~# docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED              STATUS                       PORTS               NAMES
3a3f9bda6cbd        ubuntu              "bash"              About a minute ago   Exited (127) 3 seconds ago                       wizardly_buck
26ef17bd115d        hello-world         "/hello"            8 minutes ago        Exited (0) 8 minutes ago                         angry_chaplygin

Important - Notez que chaque conteneur peut être référencé par son CONTAINER ID ou par son NAME.

Pour consulter la liste des images, utilisez la commande docker images :

root@debian9:~# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
ubuntu              latest              94e814e2efa8        4 weeks ago         88.9MB
hello-world         latest              fce289e99eb9        3 months ago        4.84kB

Important - Notez que chaque image est référencée par son IMAGE ID.

1.4 - Rechercher une Image dans un Dépôt

Pour rechercher une image docker dans le dépôt par défaut, utilisez la commande docker search :

root@debian9:~# docker search --filter=stars=5 centos
NAME                              DESCRIPTION                                     STARS               OFFICIAL            AUTOMATED
centos                            The official build of CentOS.                   5288                [OK]                
ansible/centos7-ansible           Ansible on Centos7                              121                                     [OK]
jdeathe/centos-ssh                CentOS-6 6.10 x86_64 / CentOS-7 7.5.1804 x86…   107                                     [OK]
consol/centos-xfce-vnc            Centos container with "headless" VNC session…   84                                      [OK]
imagine10255/centos6-lnmp-php56   centos6-lnmp-php56                              53                                      [OK]
centos/mysql-57-centos7           MySQL 5.7 SQL database server                   50                                      
tutum/centos                      Simple CentOS docker image with SSH access      44                                      
gluster/gluster-centos            Official GlusterFS Image [ CentOS-7 +  Glust…   40                                      [OK]
openshift/base-centos7            A Centos7 derived base image for Source-To-I…   40                                      
centos/postgresql-96-centos7      PostgreSQL is an advanced Object-Relational …   37                                      
centos/python-35-centos7          Platform for building and running Python 3.5…   34                                      
kinogmt/centos-ssh                CentOS with SSH                                 26                                      [OK]
centos/httpd-24-centos7           Platform for running Apache httpd 2.4 or bui…   22                                      
centos/php-56-centos7             Platform for building and running PHP 5.6 ap…   20                                      
openshift/jenkins-2-centos7       A Centos7 based Jenkins v2.x image for use w…   20                                      
pivotaldata/centos-gpdb-dev       CentOS image for GPDB development. Tag names…   10                                      
openshift/wildfly-101-centos7     A Centos7 based WildFly v10.1 image for use …   6                      

Important - Notez que chaque image est référencée par la colonne NAME. Le NAME est sous le format repository/mainteneur/nom sauf dans le cas où il s'agit de l'image “officielle” de l'éditeur au quel cas le format est simplement repository/nom. La notion de STARS ( étoiles ) vient de Docker Hub et est une indication de la satisfaction de la communauté.

1.5 - Supprimer un Conteneur d'une Image

Pour supprimer un conteneur d'une image, il convient d'utiliser la commande docker rm en référencant le conteneur soit par son NAME soit par son CONTAINER ID :

root@debian9:~# docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                       PORTS               NAMES
3a3f9bda6cbd        ubuntu              "bash"              7 minutes ago       Exited (127) 5 minutes ago                       wizardly_buck
26ef17bd115d        hello-world         "/hello"            13 minutes ago      Exited (0) 13 minutes ago                        angry_chaplygin
root@debian9:~# docker rm wizardly_buck
wizardly_buck
root@debian9:~# docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                      PORTS               NAMES
26ef17bd115d        hello-world         "/hello"            14 minutes ago      Exited (0) 14 minutes ago                       angry_chaplygin
root@debian9:~# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
ubuntu              latest              94e814e2efa8        4 weeks ago         88.9MB
hello-world         latest              fce289e99eb9        3 months ago        4.84kB

Important - Notez que dans le cas de l'utilisation du CONTAINER ID, il n'est pas necéssaire d'utiliser la totalité de l'ID. Par exemple, dans le cas ci-dessus, le CONTAINER ID du conteneur wizardly_buck était 3a3f9bda6cbd. La commande de suppression aurait pu utilisé 3a3f9bda6cbd, 3a3f9b ou même 3a3.

1.6 -Créer une Image à partir d'un Conteneur Modifié

Modifier un conteneur d'une image :

root@debian9:~# docker run -it ubuntu
root@54b0dae2f3a9:/# ls
bin  boot  dev  etc  home  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
root@54b0dae2f3a9:/# rm -rf /home
root@54b0dae2f3a9:/# ls
bin  boot  dev  etc  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
root@54b0dae2f3a9:/# exit
exit
root@debian9:~# 

Important - Notez ici la suppression du répertoire home dans le conteneur 54b0dae2f3a9.

Consultez la différence entre le conteneur et l'image de base :

root@debian9:~# docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED              STATUS                          PORTS               NAMES
54b0dae2f3a9        ubuntu              "/bin/bash"         About a minute ago   Exited (0) About a minute ago                       tender_mendeleev
26ef17bd115d        hello-world         "/hello"            18 minutes ago       Exited (0) 18 minutes ago                           angry_chaplygin
root@debian9:~# docker diff tender_mendeleev
C /root
A /root/.bash_history
D /home

Important - La sortie de la commande docker diff comporte des lettres dont les significations sont les suivantes : C = Create, D = Delete, A = Add.

Créez un autre conteneur à partir de l'image de base :

root@debian9:~# docker run -it ubuntu
root@92f0d4bb7967:/# ls
bin  boot  dev  etc  home  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
root@92f0d4bb7967:/# exit
exit
root@debian9:~# 

Important - Dans ce nouveau conteneur, le répertoire /home est présent compte tenu du fait qu'il a été généré à partir de l'image d'origine, inchangée depuis sa compilation.

Créez maintenant l'image ubuntu_1 à partir du conteneur competent_pasteur en utilisant la commande docker commit :

root@debian9:~# docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                      PORTS               NAMES
92f0d4bb7967        ubuntu              "/bin/bash"         39 seconds ago      Exited (0) 32 seconds ago                       musing_benz
54b0dae2f3a9        ubuntu              "/bin/bash"         3 minutes ago       Exited (0) 3 minutes ago                        tender_mendeleev
26ef17bd115d        hello-world         "/hello"            19 minutes ago      Exited (0) 19 minutes ago                       angry_chaplygin
root@debian9:~# docker commit tender_mendeleev ubuntu_1
sha256:2ba8e0ec5e38332c8ab15c4b33fd140a9c74d72231d05a6965c40a39fbb44584
root@debian9:~# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
ubuntu_1            latest              2ba8e0ec5e38        15 seconds ago      88.9MB
ubuntu              latest              94e814e2efa8        4 weeks ago         88.9MB
hello-world         latest              fce289e99eb9        3 months ago        4.84kB

1.7 - Supprimer une Image

Créez maintenant un conteneur à partir de la nouvelle image ubuntu_1 :

root@debian9:~# docker run -it ubuntu_1
root@904215fb79b4:/# ls
bin  boot  dev  etc  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
root@904215fb79b4:/# exit
exit
root@debian9:~# 

Important - Notez l'absence du répertoire home dans le conteneur 904215fb79b4.

Essayez de supprimer l'image ubuntu_1 :

root@debian9:~# docker rmi ubuntu_1
Error response from daemon: conflict: unable to remove repository reference "ubuntu_1" (must force) - container 904215fb79b4 is using its referenced image 2ba8e0ec5e38
root@debian9:~# docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED              STATUS                      PORTS               NAMES
904215fb79b4        ubuntu_1            "/bin/bash"         About a minute ago   Exited (0) 49 seconds ago                       priceless_swirles
92f0d4bb7967        ubuntu              "/bin/bash"         2 minutes ago        Exited (0) 2 minutes ago                        musing_benz
54b0dae2f3a9        ubuntu              "/bin/bash"         6 minutes ago        Exited (0) 5 minutes ago                        tender_mendeleev
26ef17bd115d        hello-world         "/hello"            22 minutes ago       Exited (0) 22 minutes ago                       angry_chaplygin

Important - Notez qu'il n'est pas possible de supprimer l'image ubuntu_1 tant que le conteneur priceless_swirles soit actif.

Supprimez donc le conteneur priceless_swirles ainsi que l'image ubuntu_1 :

root@debian9:~# docker rm priceless_swirles
priceless_swirles
root@debian9:~# docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                      PORTS               NAMES
92f0d4bb7967        ubuntu              "/bin/bash"         4 minutes ago       Exited (0) 3 minutes ago                        musing_benz
54b0dae2f3a9        ubuntu              "/bin/bash"         7 minutes ago       Exited (0) 6 minutes ago                        tender_mendeleev
26ef17bd115d        hello-world         "/hello"            23 minutes ago      Exited (0) 23 minutes ago                       angry_chaplygin
root@debian9:~# docker rmi ubuntu_1
Untagged: ubuntu_1:latest
Deleted: sha256:2ba8e0ec5e38332c8ab15c4b33fd140a9c74d72231d05a6965c40a39fbb44584
Deleted: sha256:308e9761a8fc84661e46eff564b0bbca12b458e71bdf77bf4abbb59b21efdbbe
root@debian9:~# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
ubuntu              latest              94e814e2efa8        4 weeks ago         88.9MB
hello-world         latest              fce289e99eb9        3 months ago        1.84kB

Pour pouvoir supprimer tous les conteneurs, listez-les par leur Container ID :

root@debian9:~# docker ps -aq
92f0d4bb7967
54b0dae2f3a9
26ef17bd115d

Supprimer toutes les conteneurs :

root@debian9:~# docker rm `docker ps -aq`
92f0d4bb7967
54b0dae2f3a9
26ef17bd115d
root@debian9:~# docker ps -aq
root@debian9:~# 

Pour supprimer un conteneur dès la fin de son exécution, utilisez l'option –rm :

root@debian9:~# docker run -it --rm ubuntu
root@d123b0112fc2:/# ls
bin  boot  dev  etc  home  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
root@d123b0112fc2:/# exit
exit
root@debian9:~# docker ps -aq
root@debian9:~# 

1.8 - Créer un Conteneur avec un Nom Spécifique

Créez maintenant un conteneur avec un nom spécifique :

root@debian9:~# docker run -it --name=i2tch ubuntu
root@04b5ab87539a:/# ls
bin  boot  dev  etc  home  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
root@04b5ab87539a:/# exit
exit
root@debian9:~# docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                     PORTS               NAMES
04b5ab87539a        ubuntu              "/bin/bash"         11 seconds ago      Exited (0) 4 seconds ago                       i2tch

Pour obtenir de l'information concernant un conteneur, utilisez la commande docker inspect :

root@debian9:~# docker inspect i2tch
[
    {
        "Id": "04b5ab87539aed114cbfc3ba15d10be61cd88b9cffc88c6de9bd26e203b363b5",
        "Created": "2019-04-09T14:22:45.623162229Z",
        "Path": "/bin/bash",
        "Args": [],
        "State": {
            "Status": "exited",
            "Running": false,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 0,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2019-04-09T14:22:46.301514689Z",
            "FinishedAt": "2019-04-09T14:22:51.91071787Z"
        },
        "Image": "sha256:94e814e2efa8845d95b2112d54497fbad173e45121ce9255b93401392f538499",
        "ResolvConfPath": "/var/lib/docker/containers/04b5ab87539aed114cbfc3ba15d10be61cd88b9cffc88c6de9bd26e203b363b5/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/04b5ab87539aed114cbfc3ba15d10be61cd88b9cffc88c6de9bd26e203b363b5/hostname",
        "HostsPath": "/var/lib/docker/containers/04b5ab87539aed114cbfc3ba15d10be61cd88b9cffc88c6de9bd26e203b363b5/hosts",
        "LogPath": "/var/lib/docker/containers/04b5ab87539aed114cbfc3ba15d10be61cd88b9cffc88c6de9bd26e203b363b5/04b5ab87539aed114cbfc3ba15d10be61cd88b9cffc88c6de9bd26e203b363b5-json.log",
        "Name": "/i2tch",
        "RestartCount": 0,
        "Driver": "overlay2",
        "Platform": "linux",
        "MountLabel": "",
        "ProcessLabel": "",
        "AppArmorProfile": "",
        "ExecIDs": null,
        "HostConfig": {
            "Binds": null,
            "ContainerIDFile": "",
            "LogConfig": {
                "Type": "json-file",
                "Config": {}
            },
            "NetworkMode": "default",
            "PortBindings": {},
            "RestartPolicy": {
                "Name": "no",
                "MaximumRetryCount": 0
            },
            "AutoRemove": false,
            "VolumeDriver": "",
            "VolumesFrom": null,
            "CapAdd": null,
            "CapDrop": null,
            "Dns": [],
            "DnsOptions": [],
            "DnsSearch": [],
            "ExtraHosts": null,
            "GroupAdd": null,
            "IpcMode": "shareable",
            "Cgroup": "",
            "Links": null,
            "OomScoreAdj": 0,
            "PidMode": "",
            "Privileged": false,
            "PublishAllPorts": false,
            "ReadonlyRootfs": false,
            "SecurityOpt": null,
            "UTSMode": "",
            "UsernsMode": "",
            "ShmSize": 67108864,
            "Runtime": "runc",
            "ConsoleSize": [
                0,
                0
            ],
            "Isolation": "",
            "CpuShares": 0,
            "Memory": 0,
            "NanoCpus": 0,
            "CgroupParent": "",
            "BlkioWeight": 0,
            "BlkioWeightDevice": [],
            "BlkioDeviceReadBps": null,
            "BlkioDeviceWriteBps": null,
            "BlkioDeviceReadIOps": null,
            "BlkioDeviceWriteIOps": null,
            "CpuPeriod": 0,
            "CpuQuota": 0,
            "CpuRealtimePeriod": 0,
            "CpuRealtimeRuntime": 0,
            "CpusetCpus": "",
            "CpusetMems": "",
            "Devices": [],
            "DeviceCgroupRules": null,
            "DiskQuota": 0,
            "KernelMemory": 0,
            "MemoryReservation": 0,
            "MemorySwap": 0,
            "MemorySwappiness": null,
            "OomKillDisable": false,
            "PidsLimit": 0,
            "Ulimits": null,
            "CpuCount": 0,
            "CpuPercent": 0,
            "IOMaximumIOps": 0,
            "IOMaximumBandwidth": 0,
            "MaskedPaths": [
                "/proc/asound",
                "/proc/acpi",
                "/proc/kcore",
                "/proc/keys",
                "/proc/latency_stats",
                "/proc/timer_list",
                "/proc/timer_stats",
                "/proc/sched_debug",
                "/proc/scsi",
                "/sys/firmware"
            ],
            "ReadonlyPaths": [
                "/proc/bus",
                "/proc/fs",
                "/proc/irq",
                "/proc/sys",
                "/proc/sysrq-trigger"
            ]
        },
        "GraphDriver": {
            "Data": {
                "LowerDir": "/var/lib/docker/overlay2/1151d32cdd4dda25ee299fe2c2a8df9dcb1b7fc4c47701c2925c437fb7c3a616-init/diff:/var/lib/docker/overlay2/84bcc6977e49ee3d477255450d69b98195b721b017124194b376f6e6c0645233/diff:/var/lib/docker/overlay2/eee0d6bc849e0c074de73e17eaf11b296dd860a0fb17097f37f9af86d28dcf9b/diff:/var/lib/docker/overlay2/0deb30449649adfed4d1abb678939b2409c4804976ceea4cb75508d0fdf415b6/diff:/var/lib/docker/overlay2/a156bf77423d93e38ef326b3ca6a1d0248ce801733800dad2767070380d682b6/diff",
                "MergedDir": "/var/lib/docker/overlay2/1151d32cdd4dda25ee299fe2c2a8df9dcb1b7fc4c47701c2925c437fb7c3a616/merged",
                "UpperDir": "/var/lib/docker/overlay2/1151d32cdd4dda25ee299fe2c2a8df9dcb1b7fc4c47701c2925c437fb7c3a616/diff",
                "WorkDir": "/var/lib/docker/overlay2/1151d32cdd4dda25ee299fe2c2a8df9dcb1b7fc4c47701c2925c437fb7c3a616/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [],
        "Config": {
            "Hostname": "04b5ab87539a",
            "Domainname": "",
            "User": "",
            "AttachStdin": true,
            "AttachStdout": true,
            "AttachStderr": true,
            "Tty": true,
            "OpenStdin": true,
            "StdinOnce": true,
            "Env": [
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
            ],
            "Cmd": [
                "/bin/bash"
            ],
            "ArgsEscaped": true,
            "Image": "ubuntu",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": null,
            "OnBuild": null,
            "Labels": {}
        },
        "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "304fc54e6d23247d4faf08995b65646967670def542812d902d2ee33d178794d",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {},
            "SandboxKey": "/var/run/docker/netns/304fc54e6d23",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "",
            "Gateway": "",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "",
            "IPPrefixLen": 0,
            "IPv6Gateway": "",
            "MacAddress": "",
            "Networks": {
                "bridge": {
                    "IPAMConfig": null,
                    "Links": null,
                    "Aliases": null,
                    "NetworkID": "f2d947904cba4a871af3e50d6e1ec0a3a055849185bf7ba473b2e028880bd8a9",
                    "EndpointID": "",
                    "Gateway": "",
                    "IPAddress": "",
                    "IPPrefixLen": 0,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "MacAddress": "",
                    "DriverOpts": null
                }
            }
        }
    }
]

1.9 - Exécuter une Commande dans un Conteneur

Pour exécuter une commande spécifique dans un conteneur, passez la commande en argument :

root@debian9:~# docker run --rm ubuntu env
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
HOSTNAME=77bb110031aa
HOME=/root
root@debian9:~# 

1.10 - Injecter des Variables d'Environnement dans un Conteneur

Pour injecter une ou des variables d'environnement dans un conteneur, utilisez un fichier pré-établi :

root@debian9:~# vi env.list
root@debian9:~# cat env.list
EDITOR=vim
HOSTNAME=ubuntudocker
root@debian9:~# docker run --rm --env-file=env.list ubuntu env
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
HOSTNAME=ubuntudocker
EDITOR=vim
HOME=/root
root@debian9:~# 

1.11 - Modifier le Nom d'Hôte d'un Conteneur

Pour modifier le nom d'hôte d'un conteneur, utilisez l'option -h :

root@debian9:~# docker run -it --rm -h ubuntudocker ubuntu
root@ubuntudocker:/# hostname
ubuntudocker
root@ubuntudocker:/# exit
exit
root@debian9:~# 

1.12 - Mapper des Ports d'un Conteneur

Démarrer un conteneur de nginx sur le port localhost 81 :

root@debian9:~# docker run -it -p 81:80 nginx
Unable to find image 'nginx:latest' locally
latest: Pulling from library/nginx
27833a3ba0a5: Pull complete 
e83729dd399a: Pull complete 
ebc6a67df66d: Pull complete 
Digest: sha256:c8a861b8a1eeef6d48955a6c6d5dff8e2580f13ff4d0f549e082e7c82a8617a2
Status: Downloaded newer image for nginx:latest
^Croot@debian9:~# 

Notez que c'est bloquant. Le fait d'avoir utiliser ^C a interrompu le processus du conteneur :

^Croot@debian9:~# docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                      PORTS               NAMES
4f157e179134        nginx               "nginx -g 'daemon of…"   32 seconds ago      Exited (0) 21 seconds ago                       stoic_roentgen
04b5ab87539a        ubuntu              "/bin/bash"              5 minutes ago       Exited (0) 5 minutes ago                        i2tch

1.13 - Démarrer un Conteneur en mode Détaché

Démarrez maintenant le conteneur de nginx en mode détaché grâce à l'utilisation de l'option -d :

root@debian9:~# docker run -d -p 81:80 nginx
aabb064d4b0ade1f19216b6174631fa32a2053f6aa9d59bd724ea90ce534b004
root@debian9:~# docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED              STATUS                          PORTS                NAMES
aabb064d4b0a        nginx               "nginx -g 'daemon of…"   12 seconds ago       Up 11 seconds                   0.0.0.0:81->80/tcp   eager_lewin
4f157e179134        nginx               "nginx -g 'daemon of…"   About a minute ago   Exited (0) About a minute ago                        stoic_roentgen
04b5ab87539a        ubuntu              "/bin/bash"              6 minutes ago        Exited (0) 6 minutes ago                             i2tch

1.14 - Accèder aux Services d'un Conteneur de l'Extérieur

Installez le navigateur texte lynx :

root@debian9:~# apt-get install lynx
Lecture des listes de paquets... Fait
Construction de l'arbre des dépendances       
Lecture des informations d'état... Fait
The following additional packages will be installed:
  lynx-common
Les NOUVEAUX paquets suivants seront installés :
  lynx lynx-common
0 mis à jour, 2 nouvellement installés, 0 à enlever et 94 non mis à jour.
Il est nécessaire de prendre 1 730 ko dans les archives.
Après cette opération, 5 590 ko d'espace disque supplémentaires seront utilisés.
Souhaitez-vous continuer ? [O/n] o
Réception de:1 http://ftp.fr.debian.org/debian stretch/main amd64 lynx-common all 2.8.9dev11-1 [1 098 kB]
Réception de:2 http://ftp.fr.debian.org/debian stretch/main amd64 lynx amd64 2.8.9dev11-1 [632 kB]
1 730 ko réceptionnés en 6s (283 ko/s)                                                                                                                                  
Sélection du paquet lynx-common précédemment désélectionné.
(Lecture de la base de données... 113082 fichiers et répertoires déjà installés.)
Préparation du dépaquetage de .../lynx-common_2.8.9dev11-1_all.deb ...
Dépaquetage de lynx-common (2.8.9dev11-1) ...
Sélection du paquet lynx précédemment désélectionné.
Préparation du dépaquetage de .../lynx_2.8.9dev11-1_amd64.deb ...
Dépaquetage de lynx (2.8.9dev11-1) ...
Traitement des actions différées (« triggers ») pour mime-support (3.60) ...
Traitement des actions différées (« triggers ») pour man-db (2.7.6.1-2) ...
Paramétrage de lynx-common (2.8.9dev11-1) ...
Paramétrage de lynx (2.8.9dev11-1) ...
update-alternatives: utilisation de « /usr/bin/lynx » pour fournir « /usr/bin/www-browser » (www-browser) en mode automatique

Vérifiez que nginx répond aux requetes :

root@debian9:~# lynx --dump http://localhost:81
                               Welcome to nginx!

   If you see this page, the nginx web server is successfully installed
   and working. Further configuration is required.

   For online documentation and support please refer to [1]nginx.org.
   Commercial support is available at [2]nginx.com.

   Thank you for using nginx.

Références

   1. http://nginx.org/
   2. http://nginx.com/

1.15 - Arrêter et Démarrer un Conteneur

Arrêtez le conteneur nginx :

root@debian9:~# docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                     PORTS                NAMES
aabb064d4b0a        nginx               "nginx -g 'daemon of…"   2 minutes ago       Up 2 minutes               0.0.0.0:81->80/tcp   eager_lewin
4f157e179134        nginx               "nginx -g 'daemon of…"   4 minutes ago       Exited (0) 3 minutes ago                        stoic_roentgen
04b5ab87539a        ubuntu              "/bin/bash"              8 minutes ago       Exited (0) 8 minutes ago                        i2tch
root@debian9:~# docker stop aabb
aabb
root@debian9:~# docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                     PORTS               NAMES
aabb064d4b0a        nginx               "nginx -g 'daemon of…"   2 minutes ago       Exited (0) 2 seconds ago                       eager_lewin
4f157e179134        nginx               "nginx -g 'daemon of…"   4 minutes ago       Exited (0) 4 minutes ago                       stoic_roentgen
04b5ab87539a        ubuntu              "/bin/bash"              8 minutes ago       Exited (0) 8 minutes ago                       i2tch

Démarrez de nouveau le conteneur de nginx :

root@debian9:~# docker start aabb
aabb
root@debian9:~# docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                     PORTS                NAMES
aabb064d4b0a        nginx               "nginx -g 'daemon of…"   3 minutes ago       Up 3 seconds               0.0.0.0:81->80/tcp   eager_lewin
4f157e179134        nginx               "nginx -g 'daemon of…"   4 minutes ago       Exited (0) 4 minutes ago                        stoic_roentgen
04b5ab87539a        ubuntu              "/bin/bash"              9 minutes ago       Exited (0) 8 minutes ago                        i2tch

1.16 - Utiliser des Signaux avec un Conteneur

Utilisez un signal pour tuer le processus du conteneur de nginx :

root@debian9:~# docker kill -s 9 aabb
aabb
root@debian9:~# docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                       PORTS               NAMES
aabb064d4b0a        nginx               "nginx -g 'daemon of…"   2 hours ago         Exited (137) 2 seconds ago                       eager_lewin
4f157e179134        nginx               "nginx -g 'daemon of…"   2 hours ago         Exited (0) 2 hours ago                           stoic_roentgen
04b5ab87539a        ubuntu              "/bin/bash"              2 hours ago         Exited (0) 2 hours ago                           i2tch

Redémarrez un conteneur en cours :

root@debian9:~# docker start aabb
aabb
root@debian9:~# docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                   PORTS                NAMES
aabb064d4b0a        nginx               "nginx -g 'daemon of…"   2 hours ago         Up 1 second              0.0.0.0:81->80/tcp   eager_lewin
4f157e179134        nginx               "nginx -g 'daemon of…"   2 hours ago         Exited (0) 2 hours ago                        stoic_roentgen
04b5ab87539a        ubuntu              "/bin/bash"              2 hours ago         Exited (0) 2 hours ago                        i2tch
root@debian9:~# docker restart aabb
aabb
root@debian9:~# docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                   PORTS                NAMES
aabb064d4b0a        nginx               "nginx -g 'daemon of…"   2 hours ago         Up 2 seconds             0.0.0.0:81->80/tcp   eager_lewin
4f157e179134        nginx               "nginx -g 'daemon of…"   2 hours ago         Exited (0) 2 hours ago                        stoic_roentgen
04b5ab87539a        ubuntu              "/bin/bash"              2 hours ago         Exited (0) 2 hours ago                        i2tch

1.17 - Forcer la Suppression d'un Conteneur en cours d'Exécution

Supprimez un conteneur en cours d'exécution :

root@debian9:~# docker rm aabb
Error response from daemon: You cannot remove a running container aabb064d4b0ade1f19216b6174631fa32a2053f6aa9d59bd724ea90ce534b004. Stop the container before attempting removal or force remove
root@debian9:~# docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                   PORTS                NAMES
aabb064d4b0a        nginx               "nginx -g 'daemon of…"   2 hours ago         Up About a minute        0.0.0.0:81->80/tcp   eager_lewin
4f157e179134        nginx               "nginx -g 'daemon of…"   2 hours ago         Exited (0) 2 hours ago                        stoic_roentgen
04b5ab87539a        ubuntu              "/bin/bash"              2 hours ago         Exited (0) 2 hours ago                        i2tch
root@debian9:~# docker rm -f aabb
aabb
root@debian9:~# docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                   PORTS               NAMES
4f157e179134        nginx               "nginx -g 'daemon of…"   2 hours ago         Exited (0) 2 hours ago                       stoic_roentgen
04b5ab87539a        ubuntu              "/bin/bash"              2 hours ago         Exited (0) 2 hours ago                       i2tch

1.18 - Utilisation Simple d'un Volume

Créez le fichier index.html et placez-le dans le répertoire /root/www :

root@debian9:~# mkdir /root/www
root@debian9:~# vi index.html
root@debian9:~# cat index.html
<html>
<body>
<center>Accueil du site nginx</center>
</body>
</html>
root@debian9:~# mv index.html www/

Indiquez au conteneur que son répertoire /usr/share/nginx/html/ est remplacé par le répertoire /root/www/ de la machine hôte :

root@debian9:~# docker run -d -p 81:80 -v /root/www:/usr/share/nginx/html:ro nginx
c080793965de8a6a60db212d7e4d96de84b55352c224c054dced75b409e39bf2
root@debian9:~# lynx --dump http://localhost:81
                            Accueil du site nginx


root@debian9:~# 

Important - Notez ici l'utilisation de ro - lecture seule.

1.19 - Télécharger une image sans créer un conteneur

Téléchargez l'image de centos sans créer un conteneur :

root@debian9:~# docker pull centos
Using default tag: latest
latest: Pulling from library/centos
8ba884070f61: Pull complete 
Digest: sha256:8d487d68857f5bc9595793279b33d082b03713341ddec91054382641d14db861
Status: Downloaded newer image for centos:latest

Vérifiez le contenu de l'image en créant un conteneur :

root@debian9:~# docker run -it centos bash
[root@86252a3f00f4 /]# cat /etc/redhat-release
CentOS Linux release 7.6.1810 (Core) 
[root@86252a3f00f4 /]# rpm -qa | more
bind-license-9.9.4-73.el7_6.noarch
bash-4.2.46-31.el7.x86_64
glibc-common-2.17-260.el7_6.3.x86_64
nss-softokn-freebl-3.36.0-5.el7_5.x86_64
filesystem-3.2-25.el7.x86_64
glibc-2.17-260.el7_6.3.x86_64
nspr-4.19.0-1.el7_5.x86_64
popt-1.13-16.el7.x86_64
libcom_err-1.42.9-13.el7.x86_64
libcap-2.22-9.el7.x86_64
libstdc++-4.8.5-36.el7.x86_64
info-5.1-5.el7.x86_64
gawk-4.0.2-4.el7_3.1.x86_64
libselinux-2.5-14.1.el7.x86_64
grep-2.20-3.el7.x86_64
keyutils-libs-1.5.8-3.el7.x86_64
libverto-0.2.5-4.el7.x86_64
p11-kit-trust-0.23.5-3.el7.x86_64
openssl-libs-1.0.2k-16.el7.x86_64
krb5-libs-1.15.1-37.el7_6.x86_64
xz-libs-5.2.2-1.el7.x86_64
libdb-5.3.21-24.el7.x86_64
libgpg-error-1.12-3.el7.x86_64
libgcrypt-1.5.3-14.el7.x86_64
lua-5.1.4-15.el7.x86_64
libuuid-2.23.2-59.el7.x86_64
libmount-2.23.2-59.el7.x86_64
shared-mime-info-1.8-4.el7.x86_64
gzip-1.5-10.el7.x86_64
findutils-4.5.11-6.el7.x86_64
diffutils-3.3-4.el7.x86_64
expat-2.1.0-10.el7_3.x86_64
audit-libs-2.8.4-4.el7.x86_64
pam-1.1.8-22.el7.x86_64
nss-softokn-3.36.0-5.el7_5.x86_64
nss-3.36.0-7.1.el7_6.x86_64
libassuan-2.1.0-3.el7.x86_64
nss-tools-3.36.0-7.1.el7_6.x86_64
gobject-introspection-1.56.1-1.el7.x86_64
--More--

1.20 - S'attacher à un conteneur en cours d'exécution

Arretez le conteneur. Démarrez le conteneur puis rattachez-vous au conteneur :

[root@86252a3f00f4 /]# exit
exit
root@debian9:~# docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED              STATUS                       PORTS                NAMES
86252a3f00f4        centos              "bash"                   About a minute ago   Exited (127) 6 seconds ago                        vibrant_mccarthy
c080793965de        nginx               "nginx -g 'daemon of…"   4 minutes ago        Up 4 minutes                 0.0.0.0:81->80/tcp   suspicious_sanderson
4f157e179134        nginx               "nginx -g 'daemon of…"   3 hours ago          Exited (0) 3 hours ago                            stoic_roentgen
04b5ab87539a        ubuntu              "/bin/bash"              3 hours ago          Exited (0) 3 hours ago                            i2tch
root@debian9:~# docker start 8625
8625
root@debian9:~# docker attach 8625
[root@86252a3f00f4 /]# ls
anaconda-post.log  bin  dev  etc  home  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
[root@86252a3f00f4 /]# 

1.21 - Installer un logiciel dans le conteneur

Réparez les dépôts de CentOS 8 :

[root@86252a3f00f4 /]# sed -i 's/mirrorlist/#mirrorlist/g' /etc/yum.repos.d/CentOS-Linux-*
[root@86252a3f00f4 /]# sed -i 's|#baseurl=http://mirror.centos.org|baseurl=http://vault.centos.org|g' /etc/yum.repos.d/CentOS-Linux-*
[root@86252a3f00f4 /]# yum upgrade -y

Créez le fichier /etc/yum.repos.d/mongodb-org-4.2.repo :

[root@86252a3f00f4 /]# vi /etc/yum.repos.d/mongodb-org-4.2.repo
[root@86252a3f00f4 /]# cat /etc/yum.repos.d/mongodb-org-4.2.repo
[mongodb-org-4.2]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/4.2/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-4.2.asc
[root@86252a3f00f4 /]# 

Installez mongo :

[root@86252a3f00f4 /]# yum install -y mongodb-org

Démarrez mongod :

[root@86252a3f00f4 /]# mongod --config /etc/mongod.conf &
[1] 82
[root@86252a3f00f4 /]# about to fork child process, waiting until server is ready for connections.
forked process: 84
child process started successfully, parent exiting

[1]+  Done                    mongod --config /etc/mongod.conf
[root@86252a3f00f4 /]#  

Vérifiez que mongod est démarré :

[root@86252a3f00f4 /]# ps aux
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root         1  0.0  0.1  11828  2996 pts/0    Ss   16:57   0:00 bash
root        84  1.2  2.2 294692 46716 ?        Sl   17:16   0:00 mongod --config /etc/mongod.conf
root       103  0.0  0.1  51748  3444 pts/0    R+   17:17   0:00 ps aux

Utilisez le client mongo pour se connecter au serveur :

[root@86252a3f00f4 /]# mongo
MongoDB shell version: 4.2.2
connecting to: test
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
	http://docs.mongodb.org/
Questions? Try the support group
	http://groups.google.com/group/mongodb-user
Server has startup warnings: 
2019-04-09T17:16:26.951+0000 I CONTROL  [initandlisten] ** WARNING: You are running this process as the root user, which is not recommended.
2019-04-09T17:16:26.951+0000 I CONTROL  [initandlisten] 
> 

Sortez de mongo et du conteneur :

> exit
bye
[root@86252a3f00f4 /]# exit
exit
root@debian9:~# 

1.22 - Utilisation de la commande docker commit

Créez maintenant une nouvelle image à partir de votre conteneur :

root@debian9:~# docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                      PORTS                NAMES
86252a3f00f4        centos              "bash"                   23 minutes ago      Exited (0) 56 seconds ago                        vibrant_mccarthy
c080793965de        nginx               "nginx -g 'daemon of…"   26 minutes ago      Up 26 minutes               0.0.0.0:81->80/tcp   suspicious_sanderson
4f157e179134        nginx               "nginx -g 'daemon of…"   3 hours ago         Exited (0) 3 hours ago                           stoic_roentgen
04b5ab87539a        ubuntu              "/bin/bash"              3 hours ago         Exited (0) 3 hours ago                           i2tch
root@debian9:~# docker commit 8625 i2tch/mongodb
sha256:67afc80e1424a6d99179911ee499f6bf264faf2bc3c7ff4ac4a01ff9c23050a9

Supprimez le conteneur utilisé pour créer l'image :

root@debian9:~# docker rm 8625
8625
root@debian9:~# docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                   PORTS                NAMES
c080793965de        nginx               "nginx -g 'daemon of…"   28 minutes ago      Up 28 minutes            0.0.0.0:81->80/tcp   suspicious_sanderson
4f157e179134        nginx               "nginx -g 'daemon of…"   3 hours ago         Exited (0) 3 hours ago                        stoic_roentgen
04b5ab87539a        ubuntu              "/bin/bash"              3 hours ago         Exited (0) 3 hours ago                        i2tch

Utilisez la nouvelle image pour lancer un conteneur nommé mongo :

root@debian9:~# docker run -it --name mongo i2tch/mongodb
[root@d20fb56a38b0 /]# ls /usr/bin/mongo*
/usr/bin/mongo   /usr/bin/mongodump    /usr/bin/mongofiles   /usr/bin/mongooplog  /usr/bin/mongorestore  /usr/bin/mongostat
/usr/bin/mongod  /usr/bin/mongoexport  /usr/bin/mongoimport  /usr/bin/mongoperf   /usr/bin/mongos        /usr/bin/mongotop
[root@d20fb56a38b0 /]# ps aux
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root         1  0.1  0.1  11828  2972 pts/0    Ss   17:22   0:00 bash
root        15  0.0  0.1  51748  3468 pts/0    R+   17:23   0:00 ps aux

Editez le fichier /etc/bashrc :

[root@d20fb56a38b0 /]# echo "/usr/bin/mongod --config /etc/mongod.conf &" >> /etc/bashrc
[root@d20fb56a38b0 /]# tail /etc/bashrc
                . "$i" >/dev/null
            fi
        fi
    done

    unset i
    unset -f pathmunge
fi
# vim:ts=4:sw=4
/usr/bin/mongod --config /etc/mongod.conf &

Consultez la liste des conteneurs et relevez le CONTAINER ID du conteneur mongo :

[root@d20fb56a38b0 /]# exit
exit
root@debian9:~# docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                     PORTS                NAMES
d20fb56a38b0        i2tch/mongodb       "bash"                   2 minutes ago       Exited (0) 4 seconds ago                        mongo
c080793965de        nginx               "nginx -g 'daemon of…"   32 minutes ago      Up 32 minutes              0.0.0.0:81->80/tcp   suspicious_sanderson
4f157e179134        nginx               "nginx -g 'daemon of…"   3 hours ago         Exited (0) 3 hours ago                          stoic_roentgen
04b5ab87539a        ubuntu              "/bin/bash"              3 hours ago         Exited (0) 3 hours ago                          i2tch

Utilisez la commande commit pour “sauvegarder” la modification dans l'image :

root@debian9:~# docker commit d20f i2tch/mongodb
sha256:620057baa411b78a0030e192fdfbde0bb0c5ceae7bdeb115892d9946e542ee07

Démarrez de nouveau le conteneur pour vérifier que mongod fonctionne :

root@debian9:~# docker rm d20f
d20f
root@debian9:~# docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                   PORTS                NAMES
c080793965de        nginx               "nginx -g 'daemon of…"   33 minutes ago      Up 33 minutes            0.0.0.0:81->80/tcp   suspicious_sanderson
4f157e179134        nginx               "nginx -g 'daemon of…"   3 hours ago         Exited (0) 3 hours ago                        stoic_roentgen
04b5ab87539a        ubuntu              "/bin/bash"              3 hours ago         Exited (0) 3 hours ago                        i2tch
root@debian9:~# docker run -it --name mongo i2tch/mongodb
[root@bcec3f27ed58 /]# about to fork child process, waiting until server is ready for connections.
forked process: 16
child process started successfully, parent exiting

[1]+  Done                    /usr/bin/mongod --config /etc/mongod.conf
[root@bcec3f27ed58 /]# ps aux
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root         1  0.0  0.1  11828  2920 pts/0    Ss   17:26   0:00 bash
root        16  2.0  2.4 298788 49276 ?        Sl   17:26   0:01 /usr/bin/mongod --config /etc/mongod.conf
root        39  0.0  0.1  51748  3476 pts/0    R+   17:27   0:00 ps aux
[root@bcec3f27ed58 /]# 

1.23 - Se connecter au serveur du conteneur de l'extérieur

Pour pouvoir se connecter à mongodb depuis la machine hôte, il convient d'éditer le fichier /etc/mongod.conf :

[root@bcec3f27ed58 /]# vi /etc/mongod.conf
[root@bcec3f27ed58 /]# cat /etc/mongod.conf | grep bindIp
   bindIp: 0.0.0.0

Sortez du conteneur, re-créez une image, supprimez le conteneur utilisé et relancez de nouveau le conteneur :

[root@bcec3f27ed58 /]# exit
exit
root@debian9:~# docker commit mongo i2tch/mongodb
sha256:eca7835d4fe6a3a769046bd735ef4ad7534ac1f9bb37832d6da5db3b938d258f
root@debian9:~# docker rm mongo
mongo
root@debian9:~# docker run -it --name mongo i2tch/mongodb
[root@d2ddb4f8ca8a /]# about to fork child process, waiting until server is ready for connections.
forked process: 16
[root@d2ddb4f8ca8a /]# child process started successfully, parent exiting

[1]+  Done                    /usr/bin/mongod --config /etc/mongod.conf
[root@d2ddb4f8ca8a /]# 

Dans votre machine hôte, configurez le dépôt de mongodb :

[root@f5b45072b831 /]# exit
root@debian9:~#
root@debian9:~# apt-get install dirmngr
root@debian9:~#
root@debian9:~# apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 9DA31620334BD75D9DCB49F368818C72E52529D4
Executing: /tmp/apt-key-gpghome.xMuszKS6JM/gpg.1.sh --keyserver hkp://keyserver.ubuntu.com:80 --recv 9DA31620334BD75D9DCB49F368818C72E52529D4
gpg: key 68818C72E52529D4: public key "MongoDB 4.0 Release Signing Key <packaging@mongodb.com>" imported
gpg: Total number processed: 1
gpg:               imported: 1
root@debian9:~# 
root@debian9:~# echo "deb http://repo.mongodb.org/apt/debian stretch/mongodb-org/4.0 main" | tee /etc/apt/sources.list.d/mongodb-org-4.0.list
deb http://repo.mongodb.org/apt/debian stretch/mongodb-org/4.0 main
root@debian9:~# 
root@debian9:~# apt-get update

Cette fois, installez uniquement le client de mongodb :

root@debian9:~# apt-get install mongodb-org-shell
Lecture des listes de paquets... Fait
Construction de l'arbre des dépendances       
Lecture des informations d'état... Fait
Les NOUVEAUX paquets suivants seront installés :
  mongodb-org-shell
0 mis à jour, 1 nouvellement installés, 0 à enlever et 95 non mis à jour.
Il est nécessaire de prendre 9 809 ko dans les archives.
Après cette opération, 39,8 Mo d'espace disque supplémentaires seront utilisés.
Réception de:1 http://repo.mongodb.org/apt/debian stretch/mongodb-org/4.0/main amd64 mongodb-org-shell amd64 4.0.8 [9 809 kB]
9 809 ko réceptionnés en 7s (1 245 ko/s)                                                                                                                                
Sélection du paquet mongodb-org-shell précédemment désélectionné.
(Lecture de la base de données... 91513 fichiers et répertoires déjà installés.)
Préparation du dépaquetage de .../mongodb-org-shell_4.0.8_amd64.deb ...
Dépaquetage de mongodb-org-shell (4.0.8) ...
Paramétrage de mongodb-org-shell (4.0.8) ...
Traitement des actions différées (« triggers ») pour man-db (2.7.6.1-2) ...

Notez qu'à ce stade le conteneur ne possède pas d'adresse IP car il n'est pas démarré :

root@debian9:~# docker inspect mongo | grep IP
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "",
            "IPPrefixLen": 0,
            "IPv6Gateway": "",
                    "IPAMConfig": null,
                    "IPAddress": "",
                    "IPPrefixLen": 0,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,

Démarrez donc le conteneur et cherchez l'adresse IP de celui-ci :

root@debian9:~# docker start mongo
mongo
root@debian9:~# docker inspect mongo | grep IP
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "172.17.0.3",
            "IPPrefixLen": 16,
            "IPv6Gateway": "",
                    "IPAMConfig": null,
                    "IPAddress": "172.17.0.3",
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,

Connectez-vous maintenant à votre mongodb à partir de la machine hôte :

root@debian9:~# mongo --host 172.17.0.3
MongoDB shell version v4.0.8
connecting to: mongodb://172.17.0.3:27017/?gssapiServiceName=mongodb
WARNING: No implicit session: Logical Sessions are only supported on server versions 3.6 and greater.
Implicit session: dummy session
MongoDB server version: 4.2.2
WARNING: shell and server versions do not match
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
	http://docs.mongodb.org/
Questions? Try the support group
	http://groups.google.com/group/mongodb-user
Server has startup warnings: 
2019-04-09T17:31:33.827+0000 I CONTROL  [initandlisten] ** WARNING: You are running this process as the root user, which is not recommended.
2019-04-09T17:31:33.827+0000 I CONTROL  [initandlisten] 
>   

Copyright © 2022 Hugh Norris.

Menu