Ceci est une ancienne révision du document !


Table des matières

Version : 2020.01

Dernière mise-à-jour : 2020/07/28 13:29

DOF101 - Démarrer avec Docker

Contenu du Module

  • DOF101 - Démarrer avec Docker
    • LAB #1 - Utilisation de l'Infrastructure
      • Formations en Face-à-Face Pédagogique (FFP)
      • Formations à Distance (FAD)
        • Linux, MacOS et Windows 10 muni du client ssh
        • Windows 7 et Windows 10 sans client ssh
        • Lancement de la Machine Virtuelle Debian_9
      • Connexion à la Machine Virtuelle
        • Linux, MacOS, Windows 10 muni du client ssh et FAD
        • Windows 7 et Windows 10 sans client ssh en FFP
    • LAB #2 - Installation de Docker-CE
      • Présentation de la virtualisation
      • Présentation de Docker
      • Installer docker
    • LAB #3 - Démarrer avec Docker
      • Démarrer un Conteneur
      • Consulter la Liste des Conteneurs et Images
      • Rechercher une Image dans un Dépôt
      • Supprimer un Conteneur d'une Image
      • Créer une Image à partir d'un Conteneur Modifié
      • Supprimer une Image
      • Créer un Conteneur avec un Nom Specific
      • Exécuter une Commande dans un Conteneur
      • Injecter des Variables d'Environnement dans un Conteneur
      • Modifier le Nom d'Hôte d'un Conteneur
      • Mapper des Ports d'un Conteneur
      • Démarrer un Conteneur en mode Détaché
      • Accéder aux Services d'un Conteneur de l'Extérieur
      • Arrêter et Démarrer un Conteneur
      • Utiliser des Signaux avec un Conteneur
      • Forcer la Suppression d'un Conteneur en cours d'Exécution
      • Utilisation Simple d'un Volume
      • Télécharger une image sans créer un conteneur
      • S'attacher à un conteneur en cours d'exécution
      • Installer un logiciel dans le conteneur
      • Utilisation de la commande docker commit
      • Se connecter au serveur du conteneur de l'extérieur

LAB #1 - Utilisation de l'Infrastructure

Formations en Face-à-Face Pédagogique (FFP)

Si vous suivez cette formation en Centre de Formation, vous avez besoin d'importer la machine virtuelle qui vous a été fournie.

Ouvrez VirtualBox et importez la machine virtuelle Debian_9 :

Fichier > Importer un appareil virtuel ...

La machine virtuelle a été configurée ainsi :

Machine Nom d'hôte Adresse IP Redirection de Port
Debian_9 debian9 10.0.2.15 2022

Démarrez ensuite la machine virtuelle Debian_9.

Formations à Distance (FAD)

Vous disposez d'un serveur dédié, pré-installé, pré-configuré et hébergé dans le cloud.

Connectez-vous en ssh à votre serveur dédié :

Linux, MacOS et Windows 10 muni du client ssh

Ouvrez un terminal ou CMD et tapez la commande suivante :

$ ssh -l desktop serverXX.ittraining.network

XX représente le numéro de votre serveur dédié. Entrez ensuite le mot de passe qui vous a été fourni.

Windows 7 et Windows 10 sans client ssh

Ouvrez putty et utilisez les informations suivantes pour vous connecter à votre serveur dédié :

  • Host Name –> serverXX.ittraining.network
  • Port –> 22

Au prompt, connectez-vous en tant que desktop avec le mot de passe qui vous a été fourni.

Lancement de la Machine Virtuelle Debian_9

La machine virtuelle a été configurée ainsi :

Machine Nom d'hôte Adresse IP Redirection de Port
Debian_9 debian9 10.0.2.15 2022

Pour lancer la machine Debian_9, utilisez la commande suivante à partir de votre serveur dédié :

desktop@serverXX:~$ VBoxManage startvm Debian_9 --type headless
Waiting for VM "Debian_9" to power on...
VM "Debian_9" has been successfully started.

Connexion à la Machine Virtuelle

Les noms d'utilisateurs et les mots de passe sont :

Utilisateur Mot de Passe
trainee trainee
root fenestros

Vous devez vous connecter à la machine virtuelle Debian_9 d'une des deux façons suivantes :

Linux, MacOS, Windows 10 muni du client ssh et FAD

Ouvrez un terminal et tapez la commande suivante pour vous connecter à la machine Debian_9 :

$ ssh -l trainee localhost -p 2022

Windows 7 et Windows 10 sans client ssh en FFP

Ouvrez putty et utilisez les informations suivantes pour vous connecter à Debian_9 :

  • Host Name –> localhost
  • Port –> 2022

La Virtualisation par Isolation

Un isolateur est un logiciel qui permet d'isoler l'exécution des applications dans des containers, des contextes ou des zones d'exécution.

Historique

  • 1979 - chroot - l'isolation par changement de racine,
  • 2000 - BSD Jails - l'isolation en espace utilisateur,
  • 2004 - Solaris Containers - l'isolation par zones,
  • 2005 - OpenVZ - l'isolation par partitionnement du noyau sous Linux,
  • 2008 - LXC - LinuX Containers - l'isolation en utilisant des CGroups et des namespaces avec liblxc,
  • 2013 - Docker - l'isolation en utilisant des CGroups et des namespaces avec libcontainer,
  • 2014 - LXD - LinuX Container Daemon - l'isolation en utilisant des CGroups et des namespaces avec liblxc.

Présentation des Namespaces

Les espaces de noms permettent de regrouper des processus dans un même espace et d'attribuer des droits sur des ressources par espace. Ceci permet l'exécution de plusieurs init, chacun dans un namespace, afin de recréer un environnement pour les processus qui doivent être isolés.

Présentation des CGroups

Les Groupes de Contrôles (Control Groups) aussi appelés CGroups, sont une nouvelle façon de contrôler et de limiter des ressources. Les groupes de contrôle permettent l'allocation de ressources, même d'une manière dynamique pendant que le système fonctionne, telles le temps processeur, la mémoire système, la bande réseau, ou une combinaison de ces ressources parmi des groupes de tâches (processus) définis par l'utilisateur et exécutés sur un système.

Les CGroups sont organisés de manière hiérarchique, comme des processus. Par contre, la comparaison entre les deux démontre que tandis que les processus se trouvent dans une arborescence unique descandant tous du processus init et héritant de l'environnement de leurs parents, les CGroups peuvent être multiples donnant lieu à des arborescences ou hiérarchies multiples qui héritent de certains attributs de leurs groupes de contrôle parents.

Ces hiérarchies multiples et séparés sont necéssaires parce que chaque hiérarchie est attaché à un ou plusieurs sous-système(s) aussi appelés des Contrôleurs de Ressources ou simplement des Contrôleurs. Les contrôleurs disponibles sont :

  • blkio - utilisé pour établir des limites sur l'accès des entrées/sorties à partir et depuis des périphériques blocs,
  • cpu - utilisé pour fournir aux tâches des groupes de contrôle accès au CPU grâce au planificateur,
  • cpuacct - utilisé pour produire des rapports automatiques sur les ressources CPU utilisées par les tâches dans un groupe de contrôle,
  • cpuset - utilisé pour assigner des CPU individuels sur un système multicoeur et des noeuds de mémoire à des tâches dans un groupe de contrôle,
  • devices - utilisé pour autoriser ou pour refuser l'accès des tâches aux périphériques dans un groupe de contrôle,
  • freezer - utilisé pour suspendre ou pour réactiver les tâches dans un groupe de contrôle,
  • memory - utilisé pour établir les limites d'utilisation de la mémoire par les tâches d'un groupe de contrôle et pour génèrer des rapports automatiques sur les ressources mémoire utilisées par ces tâches,
  • net_cls - utilisé pour repérer les paquets réseau avec un identifiant de classe (classid) afin de permettre au contrôleur de trafic Linux, tc, d'identifier les paquets provenant d'une tâche particulière d'un groupe de contrôle.
  • perf_event - utilisé pour permettre le monitoring des CGroups avec l'outil perf,
  • hugetlb - utilisé pour limiter des ressources sur des pages de mémoire virtuelle de grande taille.

Les hiérarchies ont des points de montage dans le répertoire /sys/fs/cgroup :

trainee@debian9:~$ su -
Mot de passe : fenestros
root@debian9:~# ls -l /sys/fs/cgroup/
total 0
dr-xr-xr-x 2 root root  0 mai   26 08:52 blkio
lrwxrwxrwx 1 root root 11 mai   26 08:52 cpu -> cpu,cpuacct
lrwxrwxrwx 1 root root 11 mai   26 08:52 cpuacct -> cpu,cpuacct
dr-xr-xr-x 2 root root  0 mai   26 08:52 cpu,cpuacct
dr-xr-xr-x 2 root root  0 mai   26 08:52 cpuset
dr-xr-xr-x 5 root root  0 mai   26 08:52 devices
dr-xr-xr-x 2 root root  0 mai   26 08:52 freezer
dr-xr-xr-x 2 root root  0 mai   26 08:52 memory
lrwxrwxrwx 1 root root 16 mai   26 08:52 net_cls -> net_cls,net_prio
dr-xr-xr-x 2 root root  0 mai   26 08:52 net_cls,net_prio
lrwxrwxrwx 1 root root 16 mai   26 08:52 net_prio -> net_cls,net_prio
dr-xr-xr-x 2 root root  0 mai   26 08:52 perf_event
dr-xr-xr-x 5 root root  0 mai   26 08:52 pids
dr-xr-xr-x 5 root root  0 mai   26 08:52 systemd

Systemd organise les processus dans chaque CGroup. Par exemple tous les processus démarrés par le serveur Apache se trouveront dans le même CGroup, y compris les scripts CGI. Ceci implique que la gestion des ressources en utilisant des hiérarchies est couplé avec l'arborescence des unités de Systemd.

En haut de l'arborescence des unités de Systemd se trouve la tranche root - -.slice, dont dépend :

  • le system.slice - l'emplacement des services système,
  • le user.slice - l'emplacement des sessions des utilisateurs,
  • le machine.slice - l'emplacement des machines virtuelles et conteneurs.

En dessous des tranches peuvent se trouver :

  • des scopes - des processus crées par fork,
  • des services - des processus créés par une Unité.

Les slices peuvent être visualisés avec la commande suivante :

root@debian9:~# systemctl list-units --type=slice
UNIT               LOAD   ACTIVE SUB    DESCRIPTION                                                                                                                      
-.slice            loaded active active Root Slice                                                                                                                       
system-getty.slice loaded active active system-getty.slice                                                                                                               
system.slice       loaded active active System Slice                                                                                                                     
user-1000.slice    loaded active active User Slice of trainee                                                                                                            
user-112.slice     loaded active active User Slice of lightdm                                                                                                            
user.slice         loaded active active User and Session Slice                                                                                                           

LOAD   = Reflects whether the unit definition was properly loaded.
ACTIVE = The high-level unit activation state, i.e. generalization of SUB.
SUB    = The low-level unit activation state, values depend on unit type.

6 loaded units listed. Pass --all to see loaded but inactive units, too.
To show all installed unit files use 'systemctl list-unit-files'.

L'arborescence des unités de Systemd est la suivante :

root@debian9:~# systemd-cgls
Control group /:
-.slice
├─user.slice
│ ├─user-112.slice
│ │ ├─user@112.service
│ │ │ ├─dbus.service
│ │ │ │ └─539 /usr/bin/dbus-daemon --session --address=systemd: --nofork --nopidfile --systemd-activation
│ │ │ ├─init.scope
│ │ │ │ ├─527 /lib/systemd/systemd --user
│ │ │ │ └─528 (sd-pam)
│ │ │ └─gvfs-daemon.service
│ │ │   └─547 /usr/lib/gvfs/gvfsd
│ │ └─session-c1.scope
│ │   ├─524 lightdm --session-child 18 21
│ │   ├─532 /usr/sbin/lightdm-gtk-greeter
│ │   ├─534 /usr/lib/at-spi2-core/at-spi-bus-launcher --launch-immediately
│ │   ├─541 /usr/bin/dbus-daemon --config-file=/usr/share/defaults/at-spi2/accessibility.conf --nofork --print-address 3
│ │   └─543 /usr/lib/at-spi2-core/at-spi2-registryd --use-gnome-session
│ └─user-1000.slice
│   ├─session-2.scope
│   │ ├─668 sshd: trainee [priv]
│   │ ├─679 sshd: trainee@pts/0
│   │ ├─680 -bash
│   │ ├─689 su -
│   │ ├─690 -su
│   │ ├─708 systemd-cgls
│   │ └─709 systemd-cgls
│   └─user@1000.service
│     └─init.scope
│       ├─670 /lib/systemd/systemd --user
│       └─671 (sd-pam)
├─init.scope
│ └─1 /sbin/init
└─system.slice
  ├─lightdm.service
  │ ├─410 /usr/sbin/lightdm
  │ ├─425 /usr/lib/xorg/Xorg :0 -seat seat0 -auth /var/run/lightdm/root/:0 -nolisten tcp vt7 -novtswitch
  │ └─588 lightdm --session-child 14 21
  ├─anacron.service
lines 1-39

En utilisant Systemd, plusieurs ressources peuvent être limitées :

  • CPUShares - par défault 1024,
  • MemoryLimit - limite exprimée en Mo ou en Go. Pas de valeur par défaut,
  • BlockIOWeight - valeur entre 10 et 1000. Pas de valeur par défaut,
  • StartupCPUShares - comme CPUShares mais uniquement appliqué pendant le démarrage,
  • StartupBlockIOWeight - comme BlockIOWeight mais uniquement appliqué pendant le démarrage,
  • CPUQuota - utilisé pour limiter le temps CPU, même quand le système ne fait rien.

Important : Consultez le manuel systemd.resource-control(5) pour voir les paramètres CGroup qui peuvent être passés à systemctl.

LAB #2 - Travailler avec les CGroups

2.1 - Limitation de la Mémoire

Pour travailler avec les CGroups dans Debian 9, il convient d'installer les outils nécessaires :

root@debian9:~# apt-get install libcgroup1 cgroup-tools

Commencez ensuite par créer le script hello-world.sh qui servira à générer un processus pour travailler avec les CGroups :

root@debian9:~# vi hello-world.sh
root@debian9:~# cat hello-world.sh
#!/bin/bash
while [ 1 ]; do
	echo "hello world"
	sleep 60
done

Rendez le script exécutable et testez-le :

root@debian9:~# chmod u+x hello-world.sh 
root@debian9:~# ./hello-world.sh 
hello world
hello world
^C

Créez maintenant un CGroup dans le sous-système memory appelé helloworld :

root@debian9:~# mkdir /sys/fs/cgroup/memory/helloworld

Par défaut, ce CGroup héritera de l'ensemble de la mémoire disponible. Pour éviter cela, créez maintenant une limite de 40000000 octets pour ce CGroup :

root@debian9:~# echo 40000000 > /sys/fs/cgroup/memory/helloworld/memory.limit_in_bytes
root@debian9:~# cat /sys/fs/cgroup/memory/helloworld/memory.limit_in_bytes
39997440

Important - Notez que les 40 000 000 demandés sont devenus 39 997 440 ce qui correspond à un nombre entier de pages mémoire du noyau de 4Ko. ( 39 997 440 / 4096 = 9 765 ).

Lancez maintenant le script helloworld.sh :

root@debian9:~# ./hello-world.sh &
[1] 1012
root@debian9:~# hello world

root@debian9:~# ps aux | grep hello-world
root      1012  0.0  0.1  11172  2868 pts/0    S    10:24   0:00 /bin/bash ./hello-world.sh
root      1015  0.0  0.0  12784   968 pts/0    S+   10:25   0:00 grep hello-world

Notez l'héritage par défaut :

root@debian9:~# ps -ww -o cgroup 1012
CGROUP
6:devices:/user.slice,3:pids:/user.slice/user-1000.slice/session-2.scope,1:name=systemd:/user.slice/user-1000.slice/session-2.scope

Insérer le PID de notre script dans le CGroup helloworld :

root@debian9:~# echo 1012 > /sys/fs/cgroup/memory/helloworld/cgroup.procs

Notez maintenant l'héritage de la limitation de la mémoire - 2:memory:/helloworld :

root@debian9:~# ps -ww -o cgroup 1012
CGROUP
6:devices:/user.slice,3:pids:/user.slice/user-1000.slice/session-2.scope,2:memory:/helloworld,1:name=systemd:/user.slice/user-1000.slice/session-2.scope

Constatez ensuite l'occupation mémoire réelle :

root@debian9:~# cat /sys/fs/cgroup/memory/helloworld/memory.usage_in_bytes
319488

Tuez le script hello-world.sh :

root@debian9:~# kill 1012
root@debian9:~# ps aux | grep hello-world
root      1038  0.0  0.0  12784   936 pts/0    S+   10:33   0:00 grep hello-world
[1]+  Complété              ./hello-world.sh

Créez un second CGroup beaucoup plus restrictif :

root@debian9:~# mkdir /sys/fs/cgroup/memory/helloworld1
root@debian9:~# echo 6000 > /sys/fs/cgroup/memory/helloworld1/memory.limit_in_bytes
root@debian9:~# cat /sys/fs/cgroup/memory/helloworld1/memory.limit_in_bytes
4096

Relancez le script hello-world.sh et insérez-le dans le nouveau CGroup :

root@debian9:~# ./hello-world.sh &
[1] 1042
root@debian9:~# hello world

root@debian9:~# echo 1042 > /sys/fs/cgroup/memory/helloworld1/cgroup.procs

Attendez la prochaine sortie de hello world sur le canal standard puis constatez que le script s'arrête :

root@debian9:~# hello world

[1]+  Processus arrêté      ./hello-world.sh

Consultez en suite la fin du fichier /var/log/messages :

root@debian9:~# tail /var/log/messages
Jul 28 10:39:26 debian9 kernel: [ 1501.775169]  [<ffffffffabe6253d>] ? __do_page_fault+0x4bd/0x4f0
Jul 28 10:39:26 debian9 kernel: [ 1501.775171]  [<ffffffffabfc2950>] ? SyS_brk+0x160/0x180
Jul 28 10:39:26 debian9 kernel: [ 1501.775175]  [<ffffffffac41a358>] ? page_fault+0x28/0x30
Jul 28 10:39:26 debian9 kernel: [ 1501.775176] Task in /helloworld1 killed as a result of limit of /helloworld1
Jul 28 10:39:26 debian9 kernel: [ 1501.775180] memory: usage 4kB, limit 4kB, failcnt 17
Jul 28 10:39:26 debian9 kernel: [ 1501.775180] memory+swap: usage 0kB, limit 9007199254740988kB, failcnt 0
Jul 28 10:39:26 debian9 kernel: [ 1501.775181] kmem: usage 0kB, limit 9007199254740988kB, failcnt 0
Jul 28 10:39:26 debian9 kernel: [ 1501.775181] Memory cgroup stats for /helloworld1: cache:0KB rss:4KB rss_huge:0KB mapped_file:0KB dirty:0KB writeback:0KB inactive_anon:0KB active_anon:0KB inactive_file:0KB active_file:0KB unevictable:0KB
Jul 28 10:39:26 debian9 kernel: [ 1501.775188] [ pid ]   uid  tgid total_vm      rss nr_ptes nr_pmds swapents oom_score_adj name
Jul 28 10:39:26 debian9 kernel: [ 1501.775219] [ 1042]     0  1042     2795      732      10       3        0             0 hello-world.sh

Important - Notez la trace Task in /helloworld1 killed as a result of limit of /helloworld1.

2.2 - Le Paquet cgroup-tools

Le paquet cgroup-tools installe des commandes dites de facilité dont :

La commande cgcreate

Cette commande permet la création d'un CGroup :

root@debian9:~# cgcreate -g memory:helloworld2
root@debian9:~# ls -l /sys/fs/cgroup/memory/helloworld2/
total 0
-rw-r--r-- 1 root root 0 juil. 28 11:09 cgroup.clone_children
--w--w--w- 1 root root 0 juil. 28 11:09 cgroup.event_control
-rw-r--r-- 1 root root 0 juil. 28 11:09 cgroup.procs
-rw-r--r-- 1 root root 0 juil. 28 11:09 memory.failcnt
--w------- 1 root root 0 juil. 28 11:09 memory.force_empty
-rw-r--r-- 1 root root 0 juil. 28 11:09 memory.kmem.failcnt
-rw-r--r-- 1 root root 0 juil. 28 11:09 memory.kmem.limit_in_bytes
-rw-r--r-- 1 root root 0 juil. 28 11:09 memory.kmem.max_usage_in_bytes
-r--r--r-- 1 root root 0 juil. 28 11:09 memory.kmem.slabinfo
-rw-r--r-- 1 root root 0 juil. 28 11:09 memory.kmem.tcp.failcnt
-rw-r--r-- 1 root root 0 juil. 28 11:09 memory.kmem.tcp.limit_in_bytes
-rw-r--r-- 1 root root 0 juil. 28 11:09 memory.kmem.tcp.max_usage_in_bytes
-r--r--r-- 1 root root 0 juil. 28 11:09 memory.kmem.tcp.usage_in_bytes
-r--r--r-- 1 root root 0 juil. 28 11:09 memory.kmem.usage_in_bytes
-rw-r--r-- 1 root root 0 juil. 28 11:09 memory.limit_in_bytes
-rw-r--r-- 1 root root 0 juil. 28 11:09 memory.max_usage_in_bytes
-rw-r--r-- 1 root root 0 juil. 28 11:09 memory.move_charge_at_immigrate
-r--r--r-- 1 root root 0 juil. 28 11:09 memory.numa_stat
-rw-r--r-- 1 root root 0 juil. 28 11:09 memory.oom_control
---------- 1 root root 0 juil. 28 11:09 memory.pressure_level
-rw-r--r-- 1 root root 0 juil. 28 11:09 memory.soft_limit_in_bytes
-r--r--r-- 1 root root 0 juil. 28 11:09 memory.stat
-rw-r--r-- 1 root root 0 juil. 28 11:09 memory.swappiness
-r--r--r-- 1 root root 0 juil. 28 11:09 memory.usage_in_bytes
-rw-r--r-- 1 root root 0 juil. 28 11:09 memory.use_hierarchy
-rw-r--r-- 1 root root 0 juil. 28 11:09 notify_on_release
-rw-r--r-- 1 root root 0 juil. 28 11:09 tasks

Il n'existe cependant pas de commande pour affecter une limitation de la mémoire :

root@debian9:~# echo 40000000 > /sys/fs/cgroup/memory/helloworld2/memory.limit_in_bytes
La Commande cgexec

Cette commande permet d'insérer la limitation dans le CGroup et de lancer le script en une seule ligne :

root@debian9:~# cgexec -g memory:helloworld2 ./hello-world.sh &
[2] 1860
root@debian9:~# hello world

root@debian9:~#
La Commande cgdelete

Une fois le script terminé, cette commande permet de supprimer le cgroup :

root@debian9:~# ps aux | grep *.sh
root      1073  0.0  0.1  11172  2868 pts/0    S    11:18   0:00 /bin/bash ./hello-world.sh
root      1076  0.0  0.0    528     4 pts/0    R+   11:18   0:00 grep hello-world.sh
root@debian9:~# kill 1073
root@debian9:~# ps aux | grep *.sh
root      1078  0.0  0.0  12784   920 pts/0    S+   11:18   0:00 grep hello-world.sh
[1]+  Complété              cgexec -g memory:helloworld2 ./hello-world.sh
root@debian9:~# cgdelete memory:helloworld2
root@debian9:~# ls -l /sys/fs/cgroup/memory/helloworld2/
ls: impossible d'accéder à '/sys/fs/cgroup/memory/helloworld2/': Aucun fichier ou dossier de ce type
La Commande cgexec

Afin de les rendre persistents, il convient de créer les CGroups dans le fichier /etc/cgconfig.conf :

root@debian9:~# vi /etc/cgconfig.conf
root@debian9:~# cat /etc/cgconfig.conf
group helloworld2 {
	cpu {
		cpu.shares = 100;
	}
	memory {
		memory.limit_in_bytes = 40000;
	}
}

Important - Notez la création de deux limitations, une de 40 000 octets de mémoire et l'autre de 100 cpu.shares. Cette dernière est une valeur exprimée sur 1 024, où 1 024 représente 100% du temps CPU. La limite fixée est donc equivalente à 9,77% du temps CPU.

Créez donc les deux CGroups concernés :

root@debian9:~# cgcreate -g memory:helloworld2
root@debian9:~# ls -l /sys/fs/cgroup/memory/helloworld2/
total 0
-rw-r--r-- 1 root root 0 juil. 28 12:47 cgroup.clone_children
--w--w--w- 1 root root 0 juil. 28 12:47 cgroup.event_control
-rw-r--r-- 1 root root 0 juil. 28 12:47 cgroup.procs
-rw-r--r-- 1 root root 0 juil. 28 12:47 memory.failcnt
--w------- 1 root root 0 juil. 28 12:47 memory.force_empty
-rw-r--r-- 1 root root 0 juil. 28 12:47 memory.kmem.failcnt
-rw-r--r-- 1 root root 0 juil. 28 12:47 memory.kmem.limit_in_bytes
-rw-r--r-- 1 root root 0 juil. 28 12:47 memory.kmem.max_usage_in_bytes
-r--r--r-- 1 root root 0 juil. 28 12:47 memory.kmem.slabinfo
-rw-r--r-- 1 root root 0 juil. 28 12:47 memory.kmem.tcp.failcnt
-rw-r--r-- 1 root root 0 juil. 28 12:47 memory.kmem.tcp.limit_in_bytes
-rw-r--r-- 1 root root 0 juil. 28 12:47 memory.kmem.tcp.max_usage_in_bytes
-r--r--r-- 1 root root 0 juil. 28 12:47 memory.kmem.tcp.usage_in_bytes
-r--r--r-- 1 root root 0 juil. 28 12:47 memory.kmem.usage_in_bytes
-rw-r--r-- 1 root root 0 juil. 28 12:47 memory.limit_in_bytes
-rw-r--r-- 1 root root 0 juil. 28 12:47 memory.max_usage_in_bytes
-rw-r--r-- 1 root root 0 juil. 28 12:47 memory.move_charge_at_immigrate
-r--r--r-- 1 root root 0 juil. 28 12:47 memory.numa_stat
-rw-r--r-- 1 root root 0 juil. 28 12:47 memory.oom_control
---------- 1 root root 0 juil. 28 12:47 memory.pressure_level
-rw-r--r-- 1 root root 0 juil. 28 12:47 memory.soft_limit_in_bytes
-r--r--r-- 1 root root 0 juil. 28 12:47 memory.stat
-rw-r--r-- 1 root root 0 juil. 28 12:47 memory.swappiness
-r--r--r-- 1 root root 0 juil. 28 12:47 memory.usage_in_bytes
-rw-r--r-- 1 root root 0 juil. 28 12:47 memory.use_hierarchy
-rw-r--r-- 1 root root 0 juil. 28 12:47 notify_on_release
-rw-r--r-- 1 root root 0 juil. 28 12:47 tasks
root@debian9:~# cgcreate -g cpu:helloworld2
root@debian9:~# ls -l /sys/fs/cgroup/cpu/helloworld2/
total 0
-rw-r--r-- 1 root root 0 juil. 28 12:48 cgroup.clone_children
-rw-r--r-- 1 root root 0 juil. 28 12:48 cgroup.procs
-r--r--r-- 1 root root 0 juil. 28 12:48 cpuacct.stat
-rw-r--r-- 1 root root 0 juil. 28 12:48 cpuacct.usage
-r--r--r-- 1 root root 0 juil. 28 12:48 cpuacct.usage_all
-r--r--r-- 1 root root 0 juil. 28 12:48 cpuacct.usage_percpu
-r--r--r-- 1 root root 0 juil. 28 12:48 cpuacct.usage_percpu_sys
-r--r--r-- 1 root root 0 juil. 28 12:48 cpuacct.usage_percpu_user
-r--r--r-- 1 root root 0 juil. 28 12:48 cpuacct.usage_sys
-r--r--r-- 1 root root 0 juil. 28 12:48 cpuacct.usage_user
-rw-r--r-- 1 root root 0 juil. 28 12:48 cpu.cfs_period_us
-rw-r--r-- 1 root root 0 juil. 28 12:48 cpu.cfs_quota_us
-rw-r--r-- 1 root root 0 juil. 28 12:48 cpu.shares
-r--r--r-- 1 root root 0 juil. 28 12:48 cpu.stat
-rw-r--r-- 1 root root 0 juil. 28 12:48 notify_on_release
-rw-r--r-- 1 root root 0 juil. 28 12:48 tasks

Appliquez le contenu du fichier /etc/cgconfig.conf grâce à l'utilisation de la commande cgconfigparser :

root@debian9:~# cgconfigparser -l /etc/cgconfig.conf
root@debian9:~# cat /sys/fs/cgroup/memory/helloworld2/memory.limit_in_bytes
36864
root@debian9:~# cat /sys/fs/cgroup/cpu/helloworld2/cpu.shares
100

Présentation de Linux Containers

LAB #3 - Travailler avec LXC

3.1 - Installation

Les outils indispensables à l'utilisation des Linux Containers sous Debian sont inclus dans le paquet lxc :

root@debian9:~# apt update
root@debian9:~# apt install lxc

L'installation de ce paquet va créer les répertoires /usr/share/lxc/config contenant les fichiers de configurations des gabarits ainsi que le répertoire /usr/share/lxc/templates contenant fichiers de gabarits pour la création des conteneurs :

root@debian9:~# ls /usr/share/lxc
config	hooks  lxc.functions  lxc-patch.py  __pycache__  selinux  templates
root@debian9:~# ls /usr/share/lxc/config
alpine.common.conf     centos.userns.conf  debian.userns.conf	   gentoo.userns.conf	 oracle.common.conf	slackware.userns.conf	  ubuntu-cloud.userns.conf
alpine.userns.conf     common.conf	   fedora.common.conf	   nesting.conf		 oracle.userns.conf	sparclinux.common.conf	  ubuntu.common.conf
archlinux.common.conf  common.conf.d	   fedora.userns.conf	   opensuse.common.conf  plamo.common.conf	sparclinux.userns.conf	  ubuntu.lucid.conf
archlinux.userns.conf  common.seccomp	   gentoo.common.conf	   opensuse.userns.conf  plamo.userns.conf	ubuntu-cloud.common.conf  ubuntu.userns.conf
centos.common.conf     debian.common.conf  gentoo.moresecure.conf  openwrt.common.conf	 slackware.common.conf	ubuntu-cloud.lucid.conf   userns.conf
root@debian9:~# ls /usr/share/lxc/templates
lxc-alpine    lxc-archlinux  lxc-centos  lxc-debian    lxc-fedora  lxc-openmandriva  lxc-oracle  lxc-slackware	 lxc-sshd    lxc-ubuntu-cloud
lxc-altlinux  lxc-busybox    lxc-cirros  lxc-download  lxc-gentoo  lxc-opensuse      lxc-plamo	 lxc-sparclinux  lxc-ubuntu

3.2 - Création d'un Conteneur Simple

Créez un conteneur simple en utilsant la comande suivante :

root@debian9:~# lxc-create -n lxc-bb -t busybox
chmod: impossible d'accéder à '/var/lib/lxc/lxc-bb/rootfs/bin/passwd': Aucun fichier ou dossier de ce type
setting root password to "root"
Failed to change root password

Important - Notez l'utilisation de l'option -n qui permet d'associer un nom au conteneur ainsi que l'option -t qui indique le gabarit à utiliser. Notez aussi que le gabarit est référencé par le nom du fichier dans le répertoire /usr/share/lxc/templates sans son préfix lxc-.

Le backingstore ( méthode de stockage) utilisé par défaut est dir ce qui implqiue que le rootfs du conteneur se trouve sur disque dans le répertoire /var/lib/lxc/ :

root@debian9:~# ls /var/lib/lxc/
lxc-bb

root@debian9:~# ls /var/lib/lxc/lxc-bb/
config	rootfs

root@debian9:~# ls /var/lib/lxc/lxc-bb/rootfs
bin  dev  etc  home  lib  lib64  mnt  proc  root  sbin	selinux  sys  tmp  usr	var

Il est à noter que LXC peut également utiliser des backingstores de type :

  • ZFS
  • Brtfs
  • LVM
  • Loop
  • rbd (CephFS)

3.3 - Démarrage d'un Conteneur Simple

Pour démarrer le conteneur, il convient d'utiliser la commande lxc-start :

root@debian9:~# lxc-start --name lxc-bb

3.4 - S'attacher à un Conteneur Simple

Pour s'attacher au conteneur démarré, il convient d'utiliser la commande lxc-attach :

root@debian9:~# lxc-attach --name lxc-bb


BusyBox v1.22.1 (Debian 1:1.22.0-19+b3) built-in shell (ash)
Enter 'help' for a list of built-in commands.

~ # passwd
/bin/sh: passwd: not found
~ # which passwd
~ # 

Important - Notez l'absence de la commande passwd dans le conteneur, ce qui explique l'erreur lors de la création de celui-ci.

Pour sortir du conteneur, il convient d'utiliser la commande exit ou bien la combinaison de touches <Ctrl+d> :

~ # [Ctrl+d]
~ # root@debian9:~# 

Le fait de sortir du conteneur ne l'arrête pas pour autant, comme il peut être constaté par l'utilisation de la commande lxc-ls :

~ # root@debian9:~# [Entrée]
root@debian9:~# lxc-ls --running
lxc-bb 
root@debian9:~# lxc-ls -f --running
NAME   STATE   AUTOSTART GROUPS IPV4 IPV6 
lxc-bb RUNNING 0         -      -    -       

3.5 - Commandes LXC de Base

La Commande lxc-console

Pour lancer une console attachée à un TTY dans le conteneur, il convient d'utiliser la commande lxc-console :

root@debian9:~# lxc-console --name lxc-bb

Connected to tty 1
                  Type <Ctrl+a q> to exit the console, <Ctrl+a Ctrl+a> to enter Ctrl+a itself

lxc-bb login: root
Password: 
Login incorrect
lxc-bb login: trainee
Password: 
Login incorrect
lxc-bb login: 

Important - Notez que pour des raisons évidentes, le conteneur BusyBox ne sait pas gérer de logins.

Pour sortir de la console, il faut utiliser la combinaison de touches <Ctrl+a> <q> :

lxc-bb login: [Ctrl+a] [q] root@debian9:~# 
La Commande lxc-stop

Pour arrêter le conteneur, utilisez la commande lxc-stop :

root@debian9:~# lxc-ls --running
lxc-bb 
root@debian9:~# lxc-stop --name lxc-bb
root@debian9:~# lxc-ls --running
root@debian9:~# 
La Commande lxc-execute

La commande lxc-execute démarre un conteneur (qui doit être créé mais arrêté), exécute la commande passée en argument grâce aux caractères puis arrête le conteneur :

root@debian9:~# lxc-execute -n lxc-bb -- uname -a
init.lxc.static: initutils.c: mount_fs: 36 failed to mount /proc : Device or resource busy
Linux lxc-bb 4.9.0-8-amd64 #1 SMP Debian 4.9.130-2 (2018-10-27) x86_64 GNU/Linux
root@debian9:~# lxc-ls --running
root@debian9:~# 
La Commande lxc-info

Cette commande donne des informations sur un conteneur :

root@debian9:~# lxc-info -n lxc-bb
Name:           lxc-bb
State:          STOPPED
La Commande lxc-freeze

La commande lxc-freeze met en pause tous les processus du conteneur :

root@debian9:~# lxc-start -n lxc-bb 

root@debian9:~# lxc-ls --running
lxc-bb 

root@debian9:~# lxc-info -n lxc-bb
Name:           lxc-bb
State:          RUNNING
PID:            3906
CPU use:        0.00 seconds
BlkIO use:      0 bytes
Memory use:     664.00 KiB
KMem use:       340.00 KiB

root@debian9:~# lxc-freeze -n lxc-bb 

root@debian9:~# lxc-info -n lxc-bb
Name:           lxc-bb
State:          FROZEN
PID:            3906
CPU use:        0.00 seconds
BlkIO use:      0 bytes
Memory use:     664.00 KiB
KMem use:       340.00 KiB
La Commande lxc-freeze

La commande lxc-unfreeze annule l'effet d'une commande lxc-freeze précédente :

root@debian9:~# lxc-unfreeze -n lxc-bb 

root@debian9:~# lxc-info -n lxc-bb
Name:           lxc-bb
State:          RUNNING
PID:            3906
CPU use:        0.00 seconds
BlkIO use:      0 bytes
Memory use:     664.00 KiB
KMem use:       340.00 KiB

root@debian9:~# cat > /var/lib/lxc/lxc-bb/rootfs/root/hi.sh « EOF

#!/bin/bash
while [ 1 ]; do
echo “Hi”
sleep 1
done
EOF

~ # sh ./hi.sh & ~ # Hi Hi Hi Hi Hi Hi

2ième terminal

$ ssh -l trainee -p 2022 localhost trainee@localhost's password: trainee Linux debian9 4.9.0-8-amd64 #1 SMP Debian 4.9.130-2 (2018-10-27) x86_64

The programs included with the Debian GNU/Linux system are free software; the exact distribution terms for each program are described in the individual files in /usr/share/doc/*/copyright.

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent permitted by applicable law. Last login: Sun Jul 26 09:39:03 2020 from 10.0.2.2 trainee@debian9:~$ su - Mot de passe : fenestros root@debian9:~# lxc-freeze -n lxc-bb root@debian9:~# lxc-info -n lxc-bb Name: lxc-bb State: FROZEN PID: 3906 CPU use: 0.16 seconds BlkIO use: 0 bytes Memory use: 1.24 MiB KMem use: 620.00 KiB root@debian9:~#

root@debian9:~# lxc-unfreeze -n lxc-bb root@debian9:~# lxc-info -n lxc-bb Name: lxc-bb State: RUNNING PID: 3906 CPU use: 0.16 seconds BlkIO use: 0 bytes Memory use: 1.25 MiB KMem use: 632.00 KiB

root@debian9:~# lxc-cgroup -n lxc-bb -l INFO -o /dev/stdout memory.limit_in_bytes 9223372036854771712

root@debian9:~# lxc-cgroup -n lxc-bb memory.limit_in_bytes 5000 lxc-cgroup: tools/lxc_cgroup.c: main: 119 failed to assign '5000' value to 'memory.limit_in_bytes' for 'lxc-bb'

Présentation de Docker

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 necessaire 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/.

LAB #4 - Travailler avec Docker

4.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

Important - Docker est composé de trois éléments : un serveur, un client et un ou plusieur Repositories ou Dépôts. Nous reviendrons sur les dépôts dans le détail plus tard dans ce cours.

Re-démarrez la machine virtuelle avant de poursuivre :

root@debian9:~# shutdown -r now

4.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

4.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.

4.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 --stars=5 centos
Flag --stars has been deprecated, use --filter=stars=3 instead
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/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 
root@debian9:~#                    
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é.

4.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.

4.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

4.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:~# 

4.8 - Créer un Conteneur avec un Nom Spécific

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

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
                }
            }
        }
    }
]

4.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:~# 

4.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:~# 

4.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:~# 

4.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

4.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

4.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/

4.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

4.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

4.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

4.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.

4.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--

4.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 /]# 

4.21 - Installer un logiciel dans le conteneur

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:~# 

4.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 /]# 

4.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] 
>   

<html>

Copyright © 2020 Hugh Norris

</html>

Menu