Docker - Premiers pas

Docker Logo

Installation de Docker CE sur un environnement Linux

Installation sur un environnement Linux

Installation des pré requis:

sudo yum install -y yum-utils device-mapper-persistent-data lvm2

Ajout du dépôt YUM “Docker CE”:

sudo yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo

Installation de Docker CE:

sudo yum install docker-ce

Démarrage de Docker CE:

sudo systemctl start docker

Docker CLI

docker --help

Usage:  docker COMMAND

A self-sufficient runtime for containers

Options:
      --config string      Location of client config files (default "/Users/fredwork/.docker")
  -D, --debug              Enable debug mode
      --help               Print usage
  -H, --host list          Daemon socket(s) to connect to
  -l, --log-level string   Set the logging level ("debug"|"info"|"warn"|"error"|"fatal") (default "info")
      --tls                Use TLS; implied by --tlsverify
      --tlscacert string   Trust certs signed only by this CA (default "/Users/fredwork/.docker/ca.pem")
      --tlscert string     Path to TLS certificate file (default "/Users/fredwork/.docker/cert.pem")
      --tlskey string      Path to TLS key file (default "/Users/fredwork/.docker/key.pem")
      --tlsverify          Use TLS and verify the remote
  -v, --version            Print version information and quit

Management Commands:
  checkpoint  Manage checkpoints
  config      Manage Docker configs
  container   Manage containers
  image       Manage images
  network     Manage networks
  node        Manage Swarm nodes
  plugin      Manage plugins
  secret      Manage Docker secrets
  service     Manage services
  stack       Manage Docker stacks
  swarm       Manage Swarm
  system      Manage Docker
  volume      Manage volumes

Commands:
  attach      Attach local standard input, output, and error streams to a running container
  build       Build an image from a Dockerfile
  commit      Create a new image from a container's changes
  cp          Copy files/folders between a container and the local filesystem
  create      Create a new container
  deploy      Deploy a new stack or update an existing stack
  diff        Inspect changes to files or directories on a container's filesystem
  events      Get real time events from the server
  exec        Run a command in a running container
  export      Export a container's filesystem as a tar archive
  history     Show the history of an image
  images      List images
  import      Import the contents from a tarball to create a filesystem image
  info        Display system-wide information
  inspect     Return low-level information on Docker objects
  kill        Kill one or more running containers
  load        Load an image from a tar archive or STDIN
  login       Log in to a Docker registry
  logout      Log out from a Docker registry
  logs        Fetch the logs of a container
  pause       Pause all processes within one or more containers
  port        List port mappings or a specific mapping for the container
  ps          List containers
  pull        Pull an image or a repository from a registry
  push        Push an image or a repository to a registry
  rename      Rename a container
  restart     Restart one or more containers
  rm          Remove one or more containers
  rmi         Remove one or more images
  run         Run a command in a new container
  save        Save one or more images to a tar archive (streamed to STDOUT by default)
  search      Search the Docker Hub for images
  start       Start one or more stopped containers
  stats       Display a live stream of container(s) resource usage statistics
  stop        Stop one or more running containers
  tag         Create a tag TARGET\_IMAGE that refers to SOURCE_IMAGE
  top         Display the running processes of a container
  unpause     Unpause all processes within one or more containers
  update      Update configuration of one or more containers
  version     Show the Docker version information
  wait        Block until one or more containers stop, then print their exit codes

Les variables d’environnement essentielles

  • DOCKER_CONFIG : Emplacement du fichier de configurations.
  • DOCKER_HOST : Adresse de l’hôte Docker.
  • DOCKER_TMPDIR : Emplacement du répertoire temporaire de Docket.

Les commandes de base

docker ps

Affiche la liste des containers.

Exemple: Afficher la liste des conteneur démarrés

docker run -d --name demo ubuntu /usr/bin/top -b
docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
2efca9ac1fec        ubuntu              "/usr/bin/top -b"   10 minutes ago      Up 3 seconds                            demo

Exemple: afficher la liste de tous les containers, même arrêtés

docker ps --all

Exemple : Filtrer les container à afficher

docker ps --filter "name=nostalgic_stallman"
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
9b6247364a03        busybox             "top"               2 minutes ago       Up 2 minutes                            nostalgic_stallman
docker logs

Affiche les logs du conteneur.

Exemple : Nous allons démarrer un conteneur apache en mode détaché (-d) et mapper le port 80 du conteneur sur le port 8080 de l’hôte (-p 8080:80), puis afficher les logs de celui-ci.

docker run -d -p 8080:80 httpd
docker ps
CONTAINER ID        IMAGE               COMMAND              CREATED              STATUS              PORTS                          NAMES
5e740c65fea4        httpd               "httpd-foreground"   About a minute ago   Up 58 seconds       80/tcp, 0.0.0.0:80->8080/tcp   unruffled_northcutt
docker logs 5e740c65fea4
AH00558: httpd: Could not reliably determine the server's fully qualified domain name, using 172.17.0.2. Set the 'ServerName' directive globally to suppress this message
AH00558: httpd: Could not reliably determine the server's fully qualified domain name, using 172.17.0.2. Set the 'ServerName' directive globally to suppress this message
[Mon Nov 27 07:22:07.953800 2017] [mpm_event:notice] [pid 1:tid 140712807245696] AH00489: Apache/2.4.29 (Unix) configured -- resuming normal operations
[Mon Nov 27 07:22:07.953900 2017] [core:notice] [pid 1:tid 140712807245696] AH00094: Command line: 'httpd -D FOREGROUND'
curl -I http://localhost:8080/
HTTP/1.1 200 OK
Date: Mon, 27 Nov 2017 07:24:47 GMT
Server: Apache/2.4.29 (Unix)
Last-Modified: Mon, 11 Jun 2007 18:53:14 GMT
ETag: "2d-432a5e4a73a80"
Accept-Ranges: bytes
Content-Length: 45
Content-Type: text/html
docker logs 5e740c65fea4
AH00558: httpd: Could not reliably determine the server's fully qualified domain name, using 172.17.0.2. Set the 'ServerName' directive globally to suppress this message
AH00558: httpd: Could not reliably determine the server's fully qualified domain name, using 172.17.0.2. Set the 'ServerName' directive globally to suppress this message
[Mon Nov 27 07:24:43.801021 2017] [mpm_event:notice] [pid 1:tid 140441518634880] AH00489: Apache/2.4.29 (Unix) configured -- resuming normal operations
[Mon Nov 27 07:24:43.801205 2017] [core:notice] [pid 1:tid 140441518634880] AH00094: Command line: 'httpd -D FOREGROUND'
172.17.0.1 - - [27/Nov/2017:07:24:47 +0000] "HEAD / HTTP/1.1" 200 -
docker info

Affiche les informations Docker.

Exemple :

docker info
Containers: 1
 Running: 1
 Paused: 0
 Stopped: 0
Images: 1
Server Version: 17.09.0-ce
Storage Driver: overlay2
 Backing Filesystem: extfs
 Supports d_type: true
 Native Overlay Diff: true
Logging Driver: json-file
Cgroup Driver: cgroupfs
Plugins:
 Volume: local
 Network: bridge host ipvlan macvlan null overlay
 Log: awslogs fluentd gcplogs gelf journald json-file logentries splunk syslog
Swarm: inactive
Runtimes: runc
Default Runtime: runc
Init Binary: docker-init
containerd version: 06b9cb35161009dcb7123345749fef02f7cea8e0
runc version: 3f2f8b84a77f73d38244dd690525642a72156c64
init version: 949e6fa
Security Options:
 seccomp
  Profile: default
Kernel Version: 4.9.49-moby
Operating System: Alpine Linux v3.5
OSType: linux
Architecture: x86_64
CPUs: 4
Total Memory: 1.952GiB
Name: moby
ID: 4NOZ:6OBO:UBMU:GRRY:QGGH:YNMT:KLAQ:SYHV:6Q57:SJLP:T4FQ:KBKL
Docker Root Dir: /var/lib/docker
Debug Mode (client): false
Debug Mode (server): true
 File Descriptors: 25
 Goroutines: 35
 System Time: 2017-11-13T06:41:53.941477274Z
 EventsListeners: 1
No Proxy: *.local, 169.254/16
Registry: https://index.docker.io/v1/
Experimental: true
Insecure Registries:
 127.0.0.0/8
Live Restore Enabled: false
docker stats

Affiche les statistiques d’utilisation d’un container

Exemple: Afficher les stats de tous les containers démarré:

docker stats
CONTAINER           CPU %               MEM USAGE / LIMIT     MEM %               NET I/O             BLOCK I/O
1285939c1fd3        0.07%               796 KiB / 64 MiB        1.21%               788 B / 648 B       3.568 MB / 512 KB
9c76f7834ae2        0.07%               2.746 MiB / 64 MiB      4.29%               1.266 KB / 648 B    12.4 MB / 0 B
d1ea048f04e4        0.03%               4.583 MiB / 64 MiB      6.30%               2.854 KB / 648 B    27.7 MB / 0 B

Exemple: Afficher les stats d’un ou plusieurs container:

docker stats fervent_panini 5acfcb1b4fd1
CONTAINER           CPU %               MEM USAGE/LIMIT       MEM %               NET I/O
5acfcb1b4fd1        0.00%               115.2 MiB/1.045 GiB   11.03%              1.422 kB/648 B
fervent_panini      0.02%               11.08 MiB/1.045 GiB   1.06%               648 B/648 B
docker start/stop

Permet de démarrer et arrêter un container déjà présent.

Exemple:

docker start 1285939c1fd3
docker stop 1285939c1fd3
docker run

Permet de lancer un container depuis une image. Ne pas confondre avec docker start qui permet de démarrer un container déjà existant.

Exemple: Lancement d’un conteneur Ubuntu en mode interactif avec la commande bash

docker run --name test -it ubuntu

root@d6c0fe130dba:/# exit 13
echo $?
13
docker ps -a | grep test
d6c0fe130dba        ubuntu            "/bin/bash"         26 seconds ago      Exited (13) 17 seconds ago                         test

Exemple avancé: Lancement d’un conteneur détaché apache avec mapage de port et de répertoire

mkdir tmp
echo "Hello World" > tmp/index.html
docker run -d -p 8080:80 -v ~/tmp:/usr/local/apache2/htdocs httpd
curl -i http://localhost:8080/index.html
HTTP/1.1 200 OK
Date: Mon, 27 Nov 2017 07:40:20 GMT
Server: Apache/2.4.29 (Unix)
Last-Modified: Mon, 27 Nov 2017 07:40:09 GMT
ETag: "c-55ef203004840"
Accept-Ranges: bytes
Content-Length: 12
Content-Type: text/html

Hello World
docker attach

Permet d’interagir avec les entrées, sorties et erreurs d’un container

Exemple :

docker run -d --name topdemo ubuntu /usr/bin/top -b

docker attach topdemo

top - 02:05:52 up  3:05,  0 users,  load average: 0.01, 0.02, 0.05
Tasks:   1 total,   1 running,   0 sleeping,   0 stopped,   0 zombie
Cpu(s):  0.1%us,  0.2%sy,  0.0%ni, 99.7%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%st
Mem:    373572k total,   355560k used,    18012k free,    27872k buffers
Swap:   786428k total,        0k used,   786428k free,   221740k cached

PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
 1 root      20   0 17200 1116  912 R    0  0.3   0:00.03 top

 top - 02:05:55 up  3:05,  0 users,  load average: 0.01, 0.02, 0.05
 Tasks:   1 total,   1 running,   0 sleeping,   0 stopped,   0 zombie
 Cpu(s):  0.0%us,  0.2%sy,  0.0%ni, 99.8%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%st
 Mem:    373572k total,   355244k used,    18328k free,    27872k buffers
 Swap:   786428k total,        0k used,   786428k free,   221776k cached

   PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
       1 root      20   0 17208 1144  932 R    0  0.3   0:00.03 top


 top - 02:05:58 up  3:06,  0 users,  load average: 0.01, 0.02, 0.05
 Tasks:   1 total,   1 running,   0 sleeping,   0 stopped,   0 zombie
 Cpu(s):  0.2%us,  0.3%sy,  0.0%ni, 99.5%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%st
 Mem:    373572k total,   355780k used,    17792k free,    27880k buffers
 Swap:   786428k total,        0k used,   786428k free,   221776k cached

 PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
      1 root      20   0 17208 1144  932 R    0  0.3   0:00.03 top
^C$

echo $?
0
docker ps -a | grep topdemo

7998ac8581f9        ubuntu:14.04        "/usr/bin/top -b"   38 seconds ago      Exited (0) 21 seconds ago                          topdemo

Attention, la séquence de sortie CTRL+C stop le container, Dans certains cas, vous pouvez utiliser la sequence CTRL+P, CTRL+Q.

docker exec

Une autre façon d’interagir avec un conteneur démarré.

Exemple: lancer un bash dans un conteneur

docker exec -it ubuntu bash
[root@a305c9058584 /]#
docker pull

Docker pull permet de rapatrier en local une image provenant d’un repo.

Exemple: Rapatriement de l’image de Fedora en local

docker pull fedora:latest
latest: Pulling from library/fedora
a8ee583972c2: Pull complete
Digest: sha256:25f7dac76b2c88d8b7e0b1d6213d3406e77c7f230bfa1e66bd1cbb81a944eaaf
Status: Downloaded newer image for fedora:latest

Permet de chercher des images sur le registry

Exemple: Rechercher les images MySQL disponibles

docker search mysql
NAME                                                   DESCRIPTION                                     STARS               OFFICIAL            AUTOMATED
mysql                                                  MySQL is a widely used, open-source relati...   5293                [OK]
mariadb                                                MariaDB is a community-developed fork of M...   1643                [OK]
mysql/mysql-server                                     Optimized MySQL Server Docker images. Crea...   369                                     [OK]
percona                                                Percona Server is a fork of the MySQL rela...   304                 [OK]
hypriot/rpi-mysql                                      RPi-compatible Docker Image with Mysql          74
zabbix/zabbix-server-mysql                             Zabbix Server with MySQL database support       65                                      [OK]
centurylink/mysql                                      Image containing mysql. Optimized to be li...   54                                      [OK]
sameersbn/mysql                                                                                        48                                      [OK]
zabbix/zabbix-web-nginx-mysql                          Zabbix frontend based on Nginx web-server ...   39                                      [OK]
tutum/mysql                                            Base docker image to run a MySQL database ...   29
1and1internet/ubuntu-16-nginx-php-phpmyadmin-mysql-5   ubuntu-16-nginx-php-phpmyadmin-mysql-5          18                                      [OK]
schickling/mysql-backup-s3                             Backup MySQL to S3 (supports periodic back...   16                                      [OK]
centos/mysql-57-centos7                                MySQL 5.7 SQL database server                   15
linuxserver/mysql                                      A Mysql container, brought to you by Linux...   13
centos/mysql-56-centos7                                MySQL 5.6 SQL database server                   6
openshift/mysql-55-centos7                             DEPRECATED: A Centos7 based MySQL v5.5 ima...   6
frodenas/mysql                                         A Docker Image for MySQL                        3                                       [OK]
dsteinkopf/backup-all-mysql                            backup all DBs in a mysql server                3                                       [OK]
circleci/mysql                                         MySQL is a widely used, open-source relati...   2
cloudfoundry/cf-mysql-ci                               Image used in CI of cf-mysql-release            0
astronomerio/mysql-sink                                MySQL sink                                      0                                       [OK]
ansibleplaybookbundle/rhscl-mysql-apb                  An APB which deploys RHSCL MySQL                0                                       [OK]
cloudposse/mysql                                       Improved `mysql` service with support for ...   0                                       [OK]
inferlink/landmark-mysql                               landmark-mysql                                  0                                       [OK]
astronomerio/mysql-source                              MySQL source                                    0                                       [OK]

Exemple: Rechercher les images MySQL officielles disponibles

docker search --filter "is-official=true" mysql
NAME                DESCRIPTION                                     STARS               OFFICIAL            AUTOMATED
mysql               MySQL is a widely used, open-source relati...   5293                [OK]
mariadb             MariaDB is a community-developed fork of M...   1643                [OK]
percona             Percona Server is a fork of the MySQL rela...   304                 [OK]
docker images

Liste les images disponibles sur l’hôte

Exemple: afficher les images rapatriées sur l’hôte

docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
fedora              latest              422dc563ca32        13 days ago         252MB
ubuntu              latest              dd6f76d9cc90        3 weeks ago         122MB
httpd               latest              74ad7f48867f        3 weeks ago         177MB
docker rmi

Supprime une ou plusieurs images.

Exemple: Supprimer l’image httpd

docker rmi httpd
Untagged: httpd:latest
Untagged: httpd@sha256:8ac08d0fdc49f2dc83bf5dab36c029ffe7776f846617335225d2796c74a247b4
Deleted: sha256:74ad7f48867fa837faca487893a59a64648432d8a5679eb0af6693a817c28322
Deleted: sha256:6421a796b6d14dd21a634dfc41570df6c2199190a07148725c53d7cbbc9a6859
Deleted: sha256:96fdf1cfce370a1da20d3c493055e91bd90d382513bf29ab8daf32763b812227
Deleted: sha256:b3bd54e1350ee59a897ef86ca8f9f75670a3a6f492db9a764cc3c17e4a3ee19d
Deleted: sha256:904b210d996a509452e0e4fa3d2270bc3b747383d7f2ae250328a95964f773c9
Deleted: sha256:b97be506340b0b6b67482ccb64b3e810aaf46a00b51b286e35d118f3f4612b85
Deleted: sha256:fcace5557c8eed5d6fbc75b00c71a4969b3e5af7b1e914b0fb72f686ff43c0fc
Deleted: sha256:c01c63c6823dd8a296c2134ea94d31121069f1c52f8f8789836bc7ea2e5cdc93
docker push

Pousser une image sur un repository. Pour ça il faut que l’image ait préalablement été taguée avec le nom du repository.

docker push localhost:5000/debian
docker rm

Supprimer un container qui a préalablement été stoppé :

docker rm 6f5a6f8e7bdc
6f5a6f8e7bdc

Le volume éphémère de ce container est donc aussi supprimé. Si des données doivent persister, il fallait instancier le container avec des volumes persistants (options -v de docker run).

docker inspect

Extrait en JSON tous les détails d’un container ou d’une image.

Pour un container ,docker container inspect prend en argument le nom ou l’ID d’un container et renvoie un JSON avec toutes les informations :

docker container inspect xenodochial_bose
[
    {
        "Id": "b9b7e712554ec320f16cd169b73a8462e62689c949629c355beb35fa2d3c4f58",
        "Created": "2017-04-25T11:27:42.806855825Z",
        "Path": "httpd-foreground",
        "Args": [],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 25006,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2017-04-25T11:27:43.310689154Z",
            "FinishedAt": "0001-01-01T00:00:00Z"
        },
        "Image": "sha256:278cd55ca6c5d11e48af59b69f52a194098c179047e481624edc54f5407d7e38",
        "ResolvConfPath": "/var/lib/docker/containers/b9b7e712554ec320f16cd169b73a8462e62689c949629c355beb35fa2d3c4f58/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/b9b7e712554ec320f16cd169b73a8462e62689c949629c355beb35fa2d3c4f58/hostname",
        "HostsPath": "/var/lib/docker/containers/b9b7e712554ec320f16cd169b73a8462e62689c949629c355beb35fa2d3c4f58/hosts",
        "LogPath": "/var/lib/docker/containers/b9b7e712554ec320f16cd169b73a8462e62689c949629c355beb35fa2d3c4f58/b9b7e712554ec320f16cd169b73a8462e62689c949629c355beb35fa2d3c4f58-json.log",
        "Name": "/xenodochial_bose",
        "RestartCount": 0,
        "Driver": "btrfs",
        "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": "",
            "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": null,
            "BlkioDeviceReadBps": null,
            "BlkioDeviceWriteBps": null,
            "BlkioDeviceReadIOps": null,
            "BlkioDeviceWriteIOps": null,
            "CpuPeriod": 0,
            "CpuQuota": 0,
            "CpuRealtimePeriod": 0,
            "CpuRealtimeRuntime": 0,
            "CpusetCpus": "",
            "CpusetMems": "",
            "Devices": [],
            "DiskQuota": 0,
            "KernelMemory": 0,
            "MemoryReservation": 0,
            "MemorySwap": 0,
            "MemorySwappiness": -1,
            "OomKillDisable": false,
            "PidsLimit": 0,
            "Ulimits": null,
            "CpuCount": 0,
            "CpuPercent": 0,
            "IOMaximumIOps": 0,
            "IOMaximumBandwidth": 0
        },
        "GraphDriver": {
            "Name": "btrfs",
            "Data": null
        },
        "Mounts": [],
        "Config": {
            "Hostname": "b9b7e712554e",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "ExposedPorts": {
                "80/tcp": {}
            },
            "Tty": false,
            "OpenStdin": false,
            "StdinOnce": false,
            "Env": [
                "PATH=/usr/local/apache2/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
                "HTTPD_PREFIX=/usr/local/apache2",
                "NGHTTP2_VERSION=1.18.1-1",
                "OPENSSL_VERSION=1.0.2k-1~bpo8+1",
                "HTTPD_VERSION=2.4.25",
                "HTTPD_SHA1=bd6d138c31c109297da2346c6e7b93b9283993d2",
                "HTTPD_BZ2_URL=https://www.apache.org/dyn/closer.cgi?action=download&filename=httpd/httpd-2.4.25.tar.bz2",
                "HTTPD_ASC_URL=https://www.apache.org/dist/httpd/httpd-2.4.25.tar.bz2.asc"
            ],
            "Cmd": [
                "httpd-foreground"
            ],
            "ArgsEscaped": true,
            "Image": "httpd",
            "Volumes": null,
            "WorkingDir": "/usr/local/apache2",
            "Entrypoint": null,
            "OnBuild": null,
            "Labels": {}
        },
        "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "f7519259edad6f469755d282d581ae58caf36693539152efe379966cc0a8c4ee",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {
                "80/tcp": null
            },
            "SandboxKey": "/var/run/docker/netns/f7519259edad",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "5bc47fd6de309cb3a1c048dbda854878d73641c1a3cf250bdf084e1c79980a01",
            "Gateway": "10.0.22.1",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "10.0.22.2",
            "IPPrefixLen": 24,
            "IPv6Gateway": "",
            "MacAddress": "02:42:0a:00:16:02",
            "Networks": {
                "bridge": {
                    "IPAMConfig": null,
                    "Links": null,
                    "Aliases": null,
                    "NetworkID": "5792d826fa7311ba5847647d1214f1c1b242f861f18b216633c4b639d0526749",
                    "EndpointID": "5bc47fd6de309cb3a1c048dbda854878d73641c1a3cf250bdf084e1c79980a01",
                    "Gateway": "10.0.22.1",
                    "IPAddress": "10.0.22.2",
                    "IPPrefixLen": 24,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "MacAddress": "02:42:0a:00:16:02"
                }
            }
        }
    }
]

Pour une image, docker image inspect suivi d’un tag ou ID d’image donne aussi des détails sur l’image.

docker image inspect httpd:latest
[
    {
        "Id": "sha256:278cd55ca6c5d11e48af59b69f52a194098c179047e481624edc54f5407d7e38",
        "RepoTags": [
            "httpd:latest"
        ],
        "RepoDigests": [
            "httpd@sha256:fc9b21c3faf2e1aa4cbe91d60df40a0d30ff151d8a5f5228d77fe5e0a18fa3c2"
        ],
        "Parent": "",
        "Comment": "",
        "Created": "2017-03-21T20:50:57.031864898Z",
        "Container": "e31d65de9f354c45e3e36c2c7012ed1b655c95c923f7c3746ccdd12dd831d928",
        "ContainerConfig": {
            "Hostname": "7e9ec6cde4d1",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "ExposedPorts": {
                "80/tcp": {}
            },
            "Tty": false,
            "OpenStdin": false,
            "StdinOnce": false,
            "Env": [
                "PATH=/usr/local/apache2/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
                "HTTPD_PREFIX=/usr/local/apache2",
                "NGHTTP2_VERSION=1.18.1-1",
                "OPENSSL_VERSION=1.0.2k-1~bpo8+1",
                "HTTPD_VERSION=2.4.25",
                "HTTPD_SHA1=bd6d138c31c109297da2346c6e7b93b9283993d2",
                "HTTPD_BZ2_URL=https://www.apache.org/dyn/closer.cgi?action=download&filename=httpd/httpd-2.4.25.tar.bz2",
                "HTTPD_ASC_URL=https://www.apache.org/dist/httpd/httpd-2.4.25.tar.bz2.asc"
            ],
            "Cmd": [
                "/bin/sh",
                "-c",
                "#(nop) ",
                "CMD [\"httpd-foreground\"]"
            ],
            "ArgsEscaped": true,
            "Image": "sha256:ef5321464fcf877208d0ec5f3de6d55d870647e581a79f73edc9f174f5f1f3fb",
            "Volumes": null,
            "WorkingDir": "/usr/local/apache2",
            "Entrypoint": null,
            "OnBuild": [],
            "Labels": {}
        },
        "DockerVersion": "1.12.6",
        "Author": "",
        "Config": {
            "Hostname": "7e9ec6cde4d1",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "ExposedPorts": {
                "80/tcp": {}
            },
            "Tty": false,
            "OpenStdin": false,
            "StdinOnce": false,
            "Env": [
                "PATH=/usr/local/apache2/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
                "HTTPD_PREFIX=/usr/local/apache2",
                "NGHTTP2_VERSION=1.18.1-1",
                "OPENSSL_VERSION=1.0.2k-1~bpo8+1",
                "HTTPD_VERSION=2.4.25",
                "HTTPD_SHA1=bd6d138c31c109297da2346c6e7b93b9283993d2",
                "HTTPD_BZ2_URL=https://www.apache.org/dyn/closer.cgi?action=download&filename=httpd/httpd-2.4.25.tar.bz2",
                "HTTPD_ASC_URL=https://www.apache.org/dist/httpd/httpd-2.4.25.tar.bz2.asc"
            ],
            "Cmd": [
                "httpd-foreground"
            ],
            "ArgsEscaped": true,
            "Image": "sha256:ef5321464fcf877208d0ec5f3de6d55d870647e581a79f73edc9f174f5f1f3fb",
            "Volumes": null,
            "WorkingDir": "/usr/local/apache2",
            "Entrypoint": null,
            "OnBuild": [],
            "Labels": {}
        },
        "Architecture": "amd64",
        "Os": "linux",
        "Size": 176900584,
        "VirtualSize": 176900584,
        "GraphDriver": {
            "Name": "btrfs",
            "Data": null
        },
        "RootFS": {
            "Type": "layers",
            "Layers": [
                "sha256:5d6cbe0dbcf9a675e86aa0fbedf7ed8756d557c7468d6a7c64bde7fa9e029636",
                "sha256:aa4c186185aa90ac9c821a3c328cfbb21672dad969c9f9bc5151a5f4c341f970",
                "sha256:5789daa1c37df797b6c695bc763d16b3432ce75a4f41f12907515a0c1f57328d",
                "sha256:b7fac20846c1d5f8845698a1da24641adddb1fd58463341ee271d634d0ffa401",
                "sha256:10cd1ea92057c67d44ad7c4e371e087951d8be4603c863ed9e3925821768e247",
                "sha256:e70070ad9b015f9ba6dd95cda292e0606709ced91e9bdccebd9d57d0b2d23b94",
                "sha256:73ff04cf8df5d5c9a904952ea5b89a8fe29c43c83c94ee403a93ff319f543127"
            ]
        }
    }
]
docker history

Lister l’historique d’une image, c’est-à-dire la création de ses différentes couches.

docker history httpd
IMAGE               CREATED             CREATED BY                                      SIZE                COMMENT
278cd55ca6c5        4 weeks ago         /bin/sh -c #(nop)  CMD ["httpd-foreground"]     0 B
<missing>           4 weeks ago         /bin/sh -c #(nop)  EXPOSE 80/tcp                0 B
...
<missing>           4 weeks ago         /bin/sh -c #(nop) ADD file:4eedf861fb567ff...   123 MB

Cet historique correspond aux différentes étapes d’un build, ce que nous allons voir prochainement dans un autre chapitre.

Le Docker hub : ressources centralisées

Docker Hub est un service de registre basé sur le cloud qui vous permet de créer des liens vers des référentiels de code, de créer vos images et de les tester, de stocker des images poussées manuellement et des liens vers Docker Cloud. Il fournit une ressource centralisée pour la découverte d’images de conteneur, la distribution et la gestion des modifications, la collaboration entre utilisateurs et équipes et l’automatisation du flux de travail tout au long du pipeline de développement.1

Les volumes docker

Il est préférable d’utiliser les volumes pour la persistance des données générées et utilisées par les conteneurs Docker. Alors que les montages de répertoires dépendent du système de l’hôte, les volumes sont entièrement gérés par Docker. Les volumes ont plusieurs avantages sur les montages de répertoires:

  • Il est plus facile de sauvegarder ou de migrer des volumes que de lier des montages.
  • Vous pouvez gérer les volumes à l’aide des commandes Docker CLI ou de l’API Docker.
  • Les volumes peuvent être partagés plus sûrement entre plusieurs conteneurs.
  • Le contenu d’un nouveau volume peut être pré-rempli par un conteneur.
  • En outre, les volumes sont souvent un meilleur choix que les données persistantes dans la couche accessible en écriture d’un conteneur, car l’utilisation d’un volume n’augmente pas la taille des conteneurs qui l’utilisent et le contenu du volume existe en dehors du cycle de vie d’un conteneur donné.

Création de volumes

créer un volume avec la commande docker volume create.

docker volume create monvol

Lister les volumes créés avec la commande docker volume ls.

docker volume ls
DRIVER              VOLUME NAME
local               216ecde81cbada93bcdba4121d09794ff4b005361d25ee501411daf576afdee8
...
local               f2dd33891fedeaed4a6b563900f14470d91b645480d72908f3cb79bbe9ff1310
local               monvol

Afficher les informations d’un volume avec la commande docker volume inspect

docker volume inspect monvol
[
    {
        "CreatedAt": "2017-11-29T10:09:56Z",
        "Driver": "local",
        "Labels": {},
        "Mountpoint": "/var/lib/docker/volumes/monvol/_data",
        "Name": "monvol",
        "Options": {},
        "Scope": "local"
    }
]

Supprimer un volume avec la commande docker volume rm

docker volume rm monvol

Utiliser des volumes

Lancer un conteneur avec un volume

docker run -it --mount source=monvol,target=/data fedora bash

[Atelier] Mise en place d’un premier conteneur

Dans cet atelier, nous allons récupérer le conteneur officiel http 2.2. Monter un répertoire local et présenter sur le port 8080 de l’hôte.

Récupération d’un container depuis le registry

Récupération de l’image officiel httpd avec docker pull

docker pull httpd:2.2
2.2: Pulling from library/httpd
85b1f47fba49: Already exists
755e06b0aca1: Pull complete
3fb7d1d135f1: Pull complete
67c749699384: Pull complete
843c6085ce1b: Pull complete
Digest: sha256:4eceb4a355a19d6e33b51fbabe5f1a236bd7c6e370047877214459b8cf3c2362
Status: Downloaded newer image for httpd:2.2

On vérifie les images récupérées avec docker images.

docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
fedora              latest              422dc563ca32        2 weeks ago         252MB
ubuntu              latest              dd6f76d9cc90        3 weeks ago         122MB
httpd               latest              74ad7f48867f        3 weeks ago         177MB
httpd               2.2                 5a312d4f55c5        3 weeks ago         171MB

On créé l’arborescence sur l’hôte pour les fichiers html et les logs

mkdir -p docker_httpd/volumes/{html,logs}
echo "Hello World" > docker_httpd/volumes/html/index.html

Manipulation du container

Démarrage du container avec le mapage de port et de répertoire avec docker run.

docker run -d --name docker_httpd \
-v ~/docker_httpd/volumes/html:/usr/local/apache2/htdocs \
-v ~/docker_httpd/volumes/logs:/usr/local/apache2/logs \
-p 8080:80 httpd:2.2

Vérification que le container est bien Up and Running.

docker ps --filter "name=docker_httpd"
CONTAINER ID        IMAGE               COMMAND              CREATED             STATUS              PORTS                  NAMES
842a20126bfa        httpd:2.2           "httpd-foreground"   6 minutes ago       Up 6 minutes        0.0.0.0:8080->80/tcp   docker_httpd

Affichage du site.

curl -i http://localhost:8080
HTTP/1.1 200 OK
Date: Wed, 29 Nov 2017 06:42:26 GMT
Server: Apache/2.2.34 (Unix) mod_ssl/2.2.34 OpenSSL/1.0.1t DAV/2
Last-Modified: Wed, 29 Nov 2017 06:23:49 GMT
ETag: "2009c6531-c-55f192db1c740"
Accept-Ranges: bytes
Content-Length: 12
Content-Type: text/html

Hello World

Affichage des ressources utilisées par le conteneur avec docker stats.

docker stats --no-stream docker_httpd
CONTAINER           CPU %               MEM USAGE / LIMIT     MEM %               NET I/O             BLOCK I/O           PIDS
docker_httpd        0.01%               6.391MiB / 1.952GiB   0.32%               2.84kB / 638B       692kB / 0B          6

Lancement d’un benchmark et visualisation des ressources utilisées en live. Affichage des statistiques du conteneur.

docker stats docker_httpd

Sur l’autre fenêtre lancer un benchmark.

ab -n 50000 -c 5 http://localhost:8080/index.html

Affichage des logs du conteneur.

docker logs docker_httpd
...
172.17.0.1 - - [29/Nov/2017:06:54:45 +0000] "GET /index.html HTTP/1.0" 200 12
172.17.0.1 - - [29/Nov/2017:06:54:45 +0000] "GET /index.html HTTP/1.0" 200 12
172.17.0.1 - - [29/Nov/2017:06:54:45 +0000] "GET /index.html HTTP/1.0" 200 12
172.17.0.1 - - [29/Nov/2017:06:54:45 +0000] "GET /index.html HTTP/1.0" 200 12
172.17.0.1 - - [29/Nov/2017:06:54:45 +0000] "GET /index.html HTTP/1.0" 200 12

Arrêt et destruction du container

Arrêt du conteneur avec docker stop.

docker stop docker_httpd

Suppression du conteneur avec docker rm.

docker rm docker_httpd

Suppression de l’image httpd:2.2 avec docker rmi.

docker rmi httpd:2.2

Cet article fait partie d’une série sur Docker

comments powered by Disqus