Docker Swarm – Commandes utiles

DOCKER CONFIG

Commande : docker config
Usage:  docker config COMMAND

Manage Docker configs

Commands:
  create      Create a config from a file or STDIN
  inspect     Display detailed information on one or more configs
  ls          List configs
  rm          Remove one or more configs

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

 

DOCKER CONFIG CREATE

Commande : docker config create
Usage:  docker config create [OPTIONS] CONFIG file|-

Create a config from a file or STDIN

Options:
  -l, --label list               Config labels
      --template-driver string   Template driver

 

Créer une nouvelle config

echo config | docker config create config_name -

Les configs générées sont accessibles à l’intérieur des containers à la racine du système de fichiers dans un répertoire portant le nom de la config.
ex :

$ echo "This is a config" | docker config create my-config -
rpzlw2xdnm20zgle5axc499jl
$ docker config ls
ID                          NAME                CREATED             UPDATED
rpzlw2xdnm20zgle5axc499jl   my-config           15 seconds ago      15 seconds ago
$ docker service create --name redis --config=my-config redis:3.0.6

Sur le container en cours d’exécution, on peut accéder aux configs en clair :

# cat /my-config
This is a config

 

DOCKER CONFIG LS

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

List configs

Aliases:
  ls, list

Options:
  -f, --filter filter   Filter output based on conditions provided
      --format string   Pretty-print configs using a Go template
  -q, --quiet           Only display IDs

 

Lister les configs générées

docker config ls [OPTIONS]

Les configs générées sont accessibles à l’intérieur des containers à la racine du système de fichiers dans un répertoire portant le nom de la config.
ex :

$ docker config ls
ID                          NAME                CREATED             UPDATED
rpzlw2xdnm20zgle5axc499jl   my-config           15 seconds ago      15 seconds ago

 

DOCKER CONFIG INSPECT

Commande : docker config inspect
Usage:  docker config inspect [OPTIONS] CONFIG [CONFIG...]

Display detailed information on one or more configs

Options:
  -f, --format string   Format the output using the given Go template
      --pretty          Print the information in a human friendly format

 

Afficher les informations détaillées d’une ou plusieurs configs

docker config inspect [OPTIONS] config [config...]

ex :

$ docker config inspect my-config
[
    {
        "ID": "rpzlw2xdnm20zgle5axc499jl",
        "Version": {
            "Index": 645
        },
        "CreatedAt": "2018-10-24T11:30:09.914721035Z",
        "UpdatedAt": "2018-10-24T11:30:09.914721035Z",
        "Spec": {
            "Name": "my-config",
            "Labels": {},
            "Data": "VGhpcyBpcyBhIGNvbmZpZwo="
        }
    }
]
$ docker config inspect --pretty my-config
ID:                     rpzlw2xdnm20zgle5axc499jl
Name:                   my-config
Created at:             2018-10-24 11:30:09.914721035 +0000 utc
Updated at:             2018-10-24 11:30:09.914721035 +0000 utc
Data:
This is a config

 

DOCKER CONFIG RM

Commande : docker config rm
Usage:  docker config rm CONFIG [CONFIG...]

Remove one or more configs

Aliases:
  rm, remove

 

Supprimer une ou plusieurs configs

docker config rm config [config...]

ex :

$ docker config my-config
my-config

 

DOCKER NODE

Commande : docker node
Usage:	docker node COMMAND

Manage Swarm nodes

Commands:
  demote      Demote one or more nodes from manager in the swarm
  inspect     Display detailed information on one or more nodes
  ls          List nodes in the swarm
  promote     Promote one or more nodes to manager in the swarm
  ps          List tasks running on one or more nodes, defaults to current node
  rm          Remove one or more nodes from the swarm
  update      Update a node

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

 

DOCKER NODE DEMOTE

Commande : docker node demote
Usage:	docker node demote NODE [NODE...]

Demote one or more nodes from manager in the swarm

 

Destituer un manager en worker (Manager Status : Reachable ou Leader -> nothing)

$ docker node demote node [node...]

Cette commande ne peut être exécutée que sur un manager du swarm.
Equivaut à :
docker node update --role worker node
ex :

$ docker node ls
ID                            HOSTNAME            STATUS              AVAILABILITY        MANAGER STATUS      ENGINE VERSION
2tbkss0ywais935a56ejcsaj3     node1               Ready               Active              Leader              18.06.1-ce
pqyqmz0hs6y0yjmq93s5t64yh     node2               Ready               Active                                  18.06.1-ce
uof4dq49vyg81w6shkgsodjj6     node3               Ready               Active                                  18.06.1-ce
gzj3ho5iu91c5blamk4hpt5d6 *   node4               Ready               Active              Reachable           18.06.1-ce
$ docker node demote node1
Manager node1 demoted in the swarm.
$ docker node ls
ID                            HOSTNAME            STATUS              AVAILABILITY        MANAGER STATUS      ENGINE VERSION
2tbkss0ywais935a56ejcsaj3     node1               Ready               Active                                  18.06.1-ce
pqyqmz0hs6y0yjmq93s5t64yh     node2               Ready               Active                                  18.06.1-ce
uof4dq49vyg81w6shkgsodjj6     node3               Unknown             Active                                  18.06.1-ce
gzj3ho5iu91c5blamk4hpt5d6 *   node4               Ready               Active              Leader              18.06.1-ce

 

DOCKER NODE INSPECT

Commande : docker node inspect
Usage:	docker node inspect [OPTIONS] self|NODE [NODE...]

Display detailed information on one or more nodes

Options:
  -f, --format string   Format the output using the given Go template
      --pretty          Print the information in a human friendly format

 

Afficher les détails d’un node

$ docker node inspect [OPTIONS] node|self [node...]

ex :

$ docker node inspect --format '{{ .ManagerStatus.Leader }}' self
true
$ docker node inspect --format '{{ json .Description.Platform }}' node1
{"Architecture":"x86_64","OS":"linux"}
$ docker node inspect --pretty node1
ID:                     2tbkss0ywais935a56ejcsaj3
Hostname:               node1
Joined at:              2018-10-21 19:05:14.878395727 +0000 utc
Status:
 State:                 Ready
 Availability:          Active
 Address:               192.168.99.105
Manager Status:
 Address:               192.168.99.105:2377
 Raft Status:           Reachable
 Leader:                Yes
Platform:
 Operating System:      linux
 Architecture:          x86_64
Resources:
 CPUs:                  1
 Memory:                995.6MiB
Plugins:
 Log:           awslogs, fluentd, gcplogs, gelf, journald, json-file, logentries, splunk, syslog
 Network:               bridge, host, macvlan, null, overlay
 Volume:                local
Engine Version:         18.06.1-ce
Engine Labels:
 - provider=virtualbox
TLS Info:
 TrustRoot:
-----BEGIN CERTIFICATE-----
MIIBajCCARCgAwIBAgIUXIa6elKTTq0CSQUVhmfIQRHoSrYwCgYIKoZIzj0EAwIw
EzERMA8GA1UEAxMIc3dhcm0tY2EwHhcNMTgxMDIxMTkwMDAwWhcNMzgxMDE2MTkw
MDAwWjATMREwDwYDVQQDEwhzd2FybS1jYTBZMBMGByqGSM49AgEGCCqGSM49AwEH
A0IABGMlpMvLZq0801dyPKWfDgkIG2gw9YvVuB0+M/llXQF0tAj6aViUHDL9zz/h
wP4NCIvVS62EjcYBznUUwDuspmujQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMB
Af8EBTADAQH/MB0GA1UdDgQWBBRy3qXZMoadwuY4iT7/YmfOttjY+TAKBggqhkjO
PQQDAgNIADBFAiAtYZnKgoQffUWcM0CwGfspa0eyYeDtKn0n+R45Keb6ggIhAJDd
8FuL10fGSJpa5ZRarESYPODM4oWYsX+HyN12UE6C
-----END CERTIFICATE-----

 Issuer Subject:        MBMxETAPBgNVBAMTCHN3YXJtLWNh
 Issuer Public Key:     MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEYyWky8tmrTzTV3I8pZ8OCQgbaDD1i9W4HT4z+WVdAXS0CPppWJQcMv3PP+HA/g0Ii9VLrYSNxgHOdRTAO6ymaw==
true
$ docker node inspect node1
[
    {
        "ID": "2tbkss0ywais935a56ejcsaj3",
        "Version": {
            "Index": 9
        },
        "CreatedAt": "2018-10-21T19:05:14.878395727Z",
        "UpdatedAt": "2018-10-21T19:05:15.396961294Z",
        "Spec": {
            "Labels": {},
            "Role": "manager",
            "Availability": "active"
        },
        "Description": {
            "Hostname": "node1",
            "Platform": {
                "Architecture": "x86_64",
                "OS": "linux"
[...]
        "Status": {
            "State": "ready",
            "Addr": "192.168.99.105"
        },
        "ManagerStatus": {
            "Leader": true,
            "Reachability": "reachable",
            "Addr": "192.168.99.105:2377"
        }
    }
]

 

DOCKER NODE LS

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

List nodes in the swarm

Aliases:
  ls, list

Options:
  -f, --filter filter   Filter output based on conditions provided
      --format string   Pretty-print nodes using a Go template
  -q, --quiet           Only display IDs

 

Lister les nodes du swarm

$ docker node ls

Cette commande ne peut être exécutée que sur un manager du swarm.
ex :

$ docker node ls
ID                            HOSTNAME            STATUS              AVAILABILITY        MANAGER STATUS      ENGINE VERSION
2tbkss0ywais935a56ejcsaj3 *   node1               Ready               Active              Leader              18.06.1-ce
pqyqmz0hs6y0yjmq93s5t64yh     node2               Ready               Active                                  18.06.1-ce
uof4dq49vyg81w6shkgsodjj6     node3               Ready               Active                                  18.06.1-ce
gzj3ho5iu91c5blamk4hpt5d6     node4               Ready               Active                                  18.06.1-ce

 

Lister les containers de tous les nodes du swarm

$ docker node ps $(docker node ls -q)

Cette commande ne peut être exécutée que sur un manager du swarm.
ex :

$ docker node ps $(docker node ls -q) | uniq
ID                  NAME                IMAGE                   NODE                DESIRED STATE       CURRENT STATE           ERROR               PORTS
xulx09ta5erq         \_ vote.1          instavote/vote:latest   node1               Running             Running 3 minutes ago
9r8rovobe6kz         \_ vote.2          instavote/vote:latest   node2               Running             Running 3 minutes ago
kubdns26nfgn        vote.3              instavote/vote:latest   node3               Running             Running 3 minutes ago
1ul7pmfbx2f5         \_ vote.4          instavote/vote:latest   node1               Running             Running 3 minutes ago
js8q4ix0hkor         \_ vote.5          instavote/vote:latest   node2               Running             Running 3 minutes ago
p8g15xvh574k        vote.6              instavote/vote:latest   node3               Running             Running 3 minutes ago

 

DOCKER NODE PROMOTE

Commande : docker node promote
Usage:	docker node promote NODE [NODE...]

Promote one or more nodes to manager in the swarm

 

Promouvoir un worker en manager (Manager Status : nothing -> Reachable)

$ docker node promote node [node...]

Equivaut à :
docker node update --role manager node
Cette commande ne peut être exécutée que sur un manager du swarm.
ex :

$ docker node ls
ID                            HOSTNAME            STATUS              AVAILABILITY        MANAGER STATUS      ENGINE VERSION
2tbkss0ywais935a56ejcsaj3 *   node1               Ready               Active              Leader              18.06.1-ce
pqyqmz0hs6y0yjmq93s5t64yh     node2               Ready               Active                                  18.06.1-ce
uof4dq49vyg81w6shkgsodjj6     node3               Ready               Active                                  18.06.1-ce
gzj3ho5iu91c5blamk4hpt5d6     node4               Ready               Active                                  18.06.1-ce
$ docker node promote node4
Node node4 promoted to a manager in the swarm.
$ docker node ls
ID                            HOSTNAME            STATUS              AVAILABILITY        MANAGER STATUS      ENGINE VERSION
2tbkss0ywais935a56ejcsaj3 *   node1               Ready               Active              Leader              18.06.1-ce
pqyqmz0hs6y0yjmq93s5t64yh     node2               Ready               Active                                  18.06.1-ce
uof4dq49vyg81w6shkgsodjj6     node3               Ready               Active                                  18.06.1-ce
gzj3ho5iu91c5blamk4hpt5d6     node4               Ready               Active              Reachable           18.06.1-ce

 

DOCKER NODE PS

Commande : docker node ps
Usage:	docker node ps [OPTIONS] [NODE...]

List tasks running on one or more nodes, defaults to current node

Options:
  -f, --filter filter   Filter output based on conditions provided
      --format string   Pretty-print tasks using a Go template
      --no-resolve      Do not map IDs to Names
      --no-trunc        Do not truncate output
  -q, --quiet           Only display task IDs

 

Afficher la liste des tâches exécutées sur un ou plusieurs nodes

$ docker node ps [OPTIONS] [node|self...]

Si le node n’est pas spécifié, la requête est effectuée sur le node courant (self).
ex :

$ docker node ps node2
ID                  NAME                IMAGE               NODE                DESIRED STATE       CURRENT STATE           ERROR               PORTS
pecu29d1qn4y        redis.3             redis:3.0.6         node2               Running             Running 9 minutes ago
815xpfkqmflk        redis.5             redis:3.0.6         node2               Running             Running 9 minutes ago
$ docker node ps -f name=redis node3
ID                  NAME                IMAGE               NODE                DESIRED STATE       CURRENT STATE           ERROR               PORTS
qcyyv5yzd9to        redis.1             redis:3.0.6         node3               Running             Running 9 minutes ago
gz7vp0fylq34        redis.4             redis:3.0.6         node3               Running             Running 9 minutes ago
$ docker node ps --format "{{.Name}}: {{.Image}}" self
redis.2: redis:3.0.6

 

Lister les containers de tous les nodes du swarm

$ docker node ps $(docker node ls -q)

Cette commande ne peut être exécutée que sur un manager du swarm.
ex :

$ docker node ps $(docker node ls -q) | uniq
ID                  NAME                IMAGE                   NODE                DESIRED STATE       CURRENT STATE           ERROR               PORTS
xulx09ta5erq         \_ vote.1          instavote/vote:latest   node1               Running             Running 3 minutes ago
9r8rovobe6kz         \_ vote.2          instavote/vote:latest   node2               Running             Running 3 minutes ago
kubdns26nfgn        vote.3              instavote/vote:latest   node3               Running             Running 3 minutes ago
1ul7pmfbx2f5         \_ vote.4          instavote/vote:latest   node1               Running             Running 3 minutes ago
js8q4ix0hkor         \_ vote.5          instavote/vote:latest   node2               Running             Running 3 minutes ago
p8g15xvh574k        vote.6              instavote/vote:latest   node3               Running             Running 3 minutes ago

 

DOCKER NODE RM

Commande : docker node rm
Usage:	docker node rm [OPTIONS] NODE [NODE...]

Remove one or more nodes from the swarm

Aliases:
  rm, remove

Options:
  -f, --force   Force remove a node from the swarm

 

Supprimer un node du swarm

$ docker node rm [OPTIONS] node [node...]

Si le node est un manager, il doit être destitué au préalable (docker swarm demote) et doit quitter le swarm (docker swarm leave).
ex :

$ docker node rm node3
node3

 

DOCKER NODE UPDATE

Commande : docker node update
Usage:	docker node update [OPTIONS] NODE

Update a node

Options:
      --availability string   Availability of the node ("active"|"pause"|"drain")
      --label-add list        Add or update a node label (key=value)
      --label-rm list         Remove a node label if exists
      --role string           Role of the node ("worker"|"manager")

 

Modifier l’état d’un node

$ docker node update [OPTIONS] --availability active|pause|drain node

Un node est dans l’un des états suivants:

  • active : il peut recevoir des nouvelles tâches
  • pause : il ne peut pas recevoir de nouvelles tâches mais les tâches en cours restent inchangées
  • drain : il ne peut plus recevoir de nouvelles tâches et les tâches en cours sont re-schédulées sur d’autres nodes

ex :

$ docker node update --availability drain node2
node2
$ docker node ls
ID                            HOSTNAME            STATUS              AVAILABILITY        MANAGER STATUS      ENGINE VERSION
4utlhy8p0uz17rrpbd2xge7y3 *   node1               Ready               Active              Leader              18.06.1-ce
v2m9tm7glxq0x7lkeoq8f3trn     node2               Ready               Drain                                   18.06.1-ce
5x29m2b8x35n7zwzmrtrynehr     node3               Ready               Active                                  18.06.1-ce
otbllyeugyvkmieestfyvu5k4     node4               Down                Active                                  18.06.1-ce
$ docker node update --availability active node2
$ docker node update --availability pause node2

 

Modifier le rôle d’un node

$ docker node update [OPTIONS] --role worker|manager node

Equivaut à :
docker node demote|promotenode
ex :

$ docker node ls
ID                            HOSTNAME            STATUS              AVAILABILITY        MANAGER STATUS      ENGINE VERSION
5rznr7by4dtogwygntzhcl7e6 *   node1               Ready               Active              Leader              18.06.1-ce
xunnklrwajuaury684h1uz7rr     node2               Ready               Active                                  18.06.1-ce
$ docker node update --role manager node2
node2
$ docker node ls
ID                            HOSTNAME            STATUS              AVAILABILITY        MANAGER STATUS      ENGINE VERSION
5rznr7by4dtogwygntzhcl7e6 *   node1               Ready               Active              Leader              18.06.1-ce
xunnklrwajuaury684h1uz7rr     node2               Ready               Active              Reachable           18.06.1-ce
$ docker node update --role worker node2
node2
$ docker node ls
ID                            HOSTNAME            STATUS              AVAILABILITY        MANAGER STATUS      ENGINE VERSION
5rznr7by4dtogwygntzhcl7e6 *   node1               Ready               Active              Leader              18.06.1-ce
xunnklrwajuaury684h1uz7rr     node2               Ready               Active                                  18.06.1-ce

 

DOCKER SECRET

Commande : docker secret
Usage:  docker secret COMMAND

Manage Docker secrets

Options:


Commands:
  create      Create a secret from a file or STDIN as content
  inspect     Display detailed information on one or more secrets
  ls          List secrets
  rm          Remove one or more secrets

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

 

DOCKER SECRET CREATE

Commande : docker secret create
Usage:  docker secret create [OPTIONS] SECRET [file|-]

Create a secret from a file or STDIN as content

Options:
  -d, --driver string            Secret driver
  -l, --label list               Secret labels
      --template-driver string   Template driver

 

Créer un nouveau secret à partir de l’entrée standard

echo secret | docker secret create secret_name -

Les secrets générés sont accessibles à l’intérieur des containers dans le répertoire /run/secrets/ dans un répertoire portant le nom du secret.
ex :

$ echo "myuser" | docker secret create dbuser -
vlxwm1733obxdq47wyhdxyh1l
$ echo "mypass" | docker secret create dbpasswd -
nx1c6nh0fxd5jjexmrpyzqdu6
$ docker secret ls
ID                          NAME                DRIVER              CREATED             UPDATED
nx1c6nh0fxd5jjexmrpyzqdu6   dbpasswd                                9 seconds ago       9 seconds ago
vlxwm1733obxdq47wyhdxyh1l   dbuser                                  19 seconds ago      19 seconds ago
$ docker service create --name mydb --secret=dbuser --secret=dbpasswd redis:3.0.6

Sur le container en cours d’exécution, on peut accéder aux secrets en clair :

# cat /run/secrets/dbuser
myuser
# cat /run/secrets/dbpasswd
mypass

 

Créer un nouveau secret à partir d’un fichier

docker secret create secret_name filename

 

DOCKER SECRET LS

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

List secrets

Aliases:
  ls, list

Options:
  -f, --filter filter   Filter output based on conditions provided
      --format string   Pretty-print secrets using a Go template
  -q, --quiet           Only display IDs

 

Lister les secrets générés

docker secret ls [OPTIONS]

Les secrets générés sont accessibles à l’intérieur des containers dans le répertoire /run/secrets/ dans un répertoire portant le nom du secret.
ex :

$ docker secret ls
ID                          NAME                DRIVER              CREATED             UPDATED
nx1c6nh0fxd5jjexmrpyzqdu6   dbpasswd                                9 seconds ago       9 seconds ago
vlxwm1733obxdq47wyhdxyh1l   dbuser                                  19 seconds ago      19 seconds ago

 

DOCKER SECRET INSPECT

Commande : docker secret inspect
Usage:  docker secret inspect [OPTIONS] SECRET [SECRET...]

Display detailed information on one or more secrets

Options:
  -f, --format string   Format the output using the given Go template
      --pretty          Print the information in a human friendly format

 

Afficher les informations détaillées d’un ou plusieurs secrets

docker secret inspect [OPTIONS] secret [secret...]

ex :

$ docker secret inspect dbuser
[
    {
        "ID": "vlxwm1733obxdq47wyhdxyh1l",
        "Version": {
            "Index": 118
        },
        "CreatedAt": "2018-10-24T00:57:40.020453015Z",
        "UpdatedAt": "2018-10-24T00:57:40.020453015Z",
        "Spec": {
            "Name": "dbuser",
            "Labels": {}
        }
    }
]
$ docker secret inspect --pretty dbuser
ID:              vlxwm1733obxdq47wyhdxyh1l
Name:              dbuser
Driver:
Created at:        2018-10-24 00:57:40.020453015 +0000 utc
Updated at:        2018-10-24 00:57:40.020453015 +0000 utc

 

DOCKER SECRET RM

Commande : docker secret rm
Usage:  docker secret rm SECRET [SECRET...]

Remove one or more secrets

Aliases:
  rm, remove

 

Supprimer un ou plusieurs secrets

docker secret rm secret [secret...]

ex :

$ docker secret ls
ID                          NAME                DRIVER              CREATED             UPDATED
nx1c6nh0fxd5jjexmrpyzqdu6   dbpasswd                                10 hours ago        10 hours ago
vlxwm1733obxdq47wyhdxyh1l   dbuser                                  10 hours ago        10 hours ago
jkyvwo5udg4dtz7kewcfjv0g0   passwd                                  14 hours ago        14 hours ago
$ docker secret rm passwd
passwd

 

DOCKER SERVICE

Commande : docker service
Usage:	docker service COMMAND

Manage services

Commands:
  create      Create a new service
  inspect     Display detailed information on one or more services
  logs        Fetch the logs of a service or task
  ls          List services
  ps          List the tasks of one or more services
  rm          Remove one or more services
  rollback    Revert changes to a service's configuration
  scale       Scale one or multiple replicated services
  update      Update a service

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

 

DOCKER SERVICE CREATE

Commande : docker service create
Usage:	docker service create [OPTIONS] IMAGE [COMMAND] [ARG...]

Create a new service

Options:
      --config config                      Specify configurations to expose to the service
      --constraint list                    Placement constraints
      --container-label list               Container labels
      --credential-spec credential-spec    Credential spec for managed service account (Windows only)
  -d, --detach                             Exit immediately instead of waiting for the service to converge
      --dns list                           Set custom DNS servers
      --dns-option list                    Set DNS options
      --dns-search list                    Set custom DNS search domains
      --endpoint-mode string               Endpoint mode (vip or dnsrr) (default "vip")
      --entrypoint command                 Overwrite the default ENTRYPOINT of the image
  -e, --env list                           Set environment variables
      --env-file list                      Read in a file of environment variables
      --generic-resource list              User defined resources
      --group list                         Set one or more supplementary user groups for the container
      --health-cmd string                  Command to run to check health
      --health-interval duration           Time between running the check (ms|s|m|h)
      --health-retries int                 Consecutive failures needed to report unhealthy
      --health-start-period duration       Start period for the container to initialize before counting retries towards unstable (ms|s|m|h)
      --health-timeout duration            Maximum time to allow one check to run (ms|s|m|h)
      --host list                          Set one or more custom host-to-IP mappings (host:ip)
      --hostname string                    Container hostname
      --init                               Use an init inside each service container to forward signals and reap processes
      --isolation string                   Service container isolation mode
  -l, --label list                         Service labels
      --limit-cpu decimal                  Limit CPUs
      --limit-memory bytes                 Limit Memory
      --log-driver string                  Logging driver for service
      --log-opt list                       Logging driver options
      --mode string                        Service mode (replicated or global) (default "replicated")
      --mount mount                        Attach a filesystem mount to the service
      --name string                        Service name
      --network network                    Network attachments
      --no-healthcheck                     Disable any container-specified HEALTHCHECK
      --no-resolve-image                   Do not query the registry to resolve image digest and supported platforms
      --placement-pref pref                Add a placement preference
  -p, --publish port                       Publish a port as a node port
  -q, --quiet                              Suppress progress output
      --read-only                          Mount the container's root filesystem as read only
      --replicas uint                      Number of tasks
      --reserve-cpu decimal                Reserve CPUs
      --reserve-memory bytes               Reserve Memory
      --restart-condition string           Restart when condition is met ("none"|"on-failure"|"any") (default "any")
      --restart-delay duration             Delay between restart attempts (ns|us|ms|s|m|h) (default 5s)
      --restart-max-attempts uint          Maximum number of restarts before giving up
      --restart-window duration            Window used to evaluate the restart policy (ns|us|ms|s|m|h)
      --rollback-delay duration            Delay between task rollbacks (ns|us|ms|s|m|h) (default 0s)
      --rollback-failure-action string     Action on rollback failure ("pause"|"continue") (default "pause")
      --rollback-max-failure-ratio float   Failure rate to tolerate during a rollback (default 0)
      --rollback-monitor duration          Duration after each task rollback to monitor for failure (ns|us|ms|s|m|h) (default 5s)
      --rollback-order string              Rollback order ("start-first"|"stop-first") (default "stop-first")
      --rollback-parallelism uint          Maximum number of tasks rolled back simultaneously (0 to roll back all at once) (default 1)
      --secret secret                      Specify secrets to expose to the service
      --stop-grace-period duration         Time to wait before force killing a container (ns|us|ms|s|m|h) (default 10s)
      --stop-signal string                 Signal to stop the container
  -t, --tty                                Allocate a pseudo-TTY
      --update-delay duration              Delay between updates (ns|us|ms|s|m|h) (default 0s)
      --update-failure-action string       Action on update failure ("pause"|"continue"|"rollback") (default "pause")
      --update-max-failure-ratio float     Failure rate to tolerate during an update (default 0)
      --update-monitor duration            Duration after each task update to monitor for failure (ns|us|ms|s|m|h) (default 5s)
      --update-order string                Update order ("start-first"|"stop-first") (default "stop-first")
      --update-parallelism uint            Maximum number of tasks updated simultaneously (0 to update all at once) (default 1)
  -u, --user string                        Username or UID (format: [:])
      --with-registry-auth                 Send registry authentication details to swarm agents
  -w, --workdir string                     Working directory inside the container

 

Créer un nouveau service en ligne de commande

docker service create [OPTIONS] image [command] [ARG...]

ex :
Ci-dessous nous créons un service constitué de 6 tâches réparties sur 4 nodes.

$ docker service create --name vote --publish 8080:80 --replicas 6 instavote/vote
w6oq3h8zshjb4rxglhax6b6us
overall progress: 6 out of 6 tasks
1/6: running   [==================================================>]
2/6: running   [==================================================>]
3/6: running   [==================================================>]
4/6: running   [==================================================>]
5/6: running   [==================================================>]
6/6: running   [==================================================>]
verify: Service converged
$ docker service ps vote
ID                  NAME                IMAGE                   NODE                DESIRED STATE       CURRENT STATE            ERROR               PORTS
u6ft5zbc8xwz        vote.1              instavote/vote:latest   node3               Running             Running 29 seconds ago         
diftv07phzat        vote.2              instavote/vote:latest   node2               Running             Running 27 seconds ago         
k6qtg2kiewxx        vote.3              instavote/vote:latest   node3               Running             Running 29 seconds ago         
9t09sz9pr4e1        vote.4              instavote/vote:latest   node4               Running             Running 28 seconds ago         
g7dbwtofnrmt        vote.5              instavote/vote:latest   node1               Running             Running 26 seconds ago         
m9vthhag9a1o        vote.6              instavote/vote:latest   node2               Running             Running 27 seconds ago
$ docker service ls
ID                  NAME                MODE                REPLICAS            IMAGE                   PORTS
w6oq3h8zshjb        vote                replicated          6/6                 instavote/vote:latest   *:8080->80/tcp

Exemples divers :

$ docker service create --mode global --name redis2 redis:3.0.6
$ docker service create --name redis --replicas=5 redis:3.0.6
$ docker service create --name redis --secret secret.json redis:3.0.6
$ docker service create --name redis --hostname myredis redis:3.0.6

 

Créer un nouveau service en montant un volume

docker service create [OPTIONS] --mount type=volume|bind,[source=volume|/path/on/host],destination=/path/in/container[,options] image [command] [ARG...]

ex :
Volume nommé :

$ docker service create \
  --name my-service \
  --replicas 3 \
  --mount type=volume,source=my-volume,destination=/path/in/container,volume-label="color=red",volume-label="shape=round" \
  nginx:alpine

Volume anonyme :

$ docker service create \
  --name my-service \
  --replicas 3 \
  --mount type=volume,destination=/path/in/container \
  nginx:alpine

Volume de type bind :

$ docker service create \
  --name my-service \
  --mount type=bind,source=/path/on/host,destination=/path/in/container \
  nginx:alpine

 

Créer un nouveau service en spécifiant le mappage de ports

Format court :

docker service create [OPTIONS] --publish port:port image [command] [ARG...]

Format long :

docker service create [OPTIONS] --publish published=port,target=port image [command] [ARG...]

ex :
Ci-dessous nous créons un service constitué de 6 tâches réparties sur 4 nodes.

$ docker service create --name my_web --replicas 3 --publish 8080:80 nginx

Equivaut à :

$ docker service create --name my_web --replicas 3 --publish published=8080,target=80 nginx

 

DOCKER SERVICE INSPECT

Commande : docker service inspect
Usage:	docker service inspect [OPTIONS] SERVICE [SERVICE...]

Display detailed information on one or more services

Options:
  -f, --format string   Format the output using the given Go template
      --pretty          Print the information in a human friendly format

 

Afficher les informations détaillés relatives à un service

docker service inspect [OPTIONS] service [service...]

ex :

$ docker service inspect redis
[
    {
        "ID": "yi70e6urtfnhlhpwiqhul4x23",
        "Version": {
            "Index": 21
        },
        "CreatedAt": "2018-10-22T22:15:03.411349711Z",
        "UpdatedAt": "2018-10-22T22:15:03.411349711Z",
        "Spec": {
            "Name": "redis",
            "Labels": {},
            "TaskTemplate": {
                "ContainerSpec": {
                    "Image": "redis:3.0.6@sha256:6a692a76c2081888b589e26e6ec835743119fe453d67ecf03df7de5b73d69842",
                    "StopGracePeriod": 10000000000,
                    "DNSConfig": {},
                    "Isolation": "default"
[...]
           "RollbackConfig": {
                "Parallelism": 1,
                "FailureAction": "pause",
                "Monitor": 5000000000,
                "MaxFailureRatio": 0,
                "Order": "stop-first"
            },
            "EndpointSpec": {
                "Mode": "vip"
            }
        },
        "Endpoint": {
            "Spec": {}
        }
    }
]
$ docker service inspect --pretty redis

ID:             yi70e6urtfnhlhpwiqhul4x23
Name:           redis
Service Mode:   Replicated
 Replicas:      5
Placement:
UpdateConfig:
 Parallelism:   1
 On failure:    pause
 Monitoring Period: 5s
 Max failure ratio: 0
 Update order:      stop-first
RollbackConfig:
 Parallelism:   1
 On failure:    pause
 Monitoring Period: 5s
 Max failure ratio: 0
 Rollback order:    stop-first
ContainerSpec:
 Image:         redis:3.0.6@sha256:6a692a76c2081888b589e26e6ec835743119fe453d67ecf03df7de5b73d69842
Resources:
Endpoint Mode:  vip
$ docker service inspect --format='{{.Spec.Mode.Replicated.Replicas}}' redis
5

 

DOCKER SERVICE LOGS

Commande : docker service logs
Usage:	docker service logs [OPTIONS] SERVICE|TASK

Fetch the logs of a service or task

Options:
      --details        Show extra details provided to logs
  -f, --follow         Follow log output
      --no-resolve     Do not map IDs to Names in output
      --no-task-ids    Do not include task IDs in output
      --no-trunc       Do not truncate output
      --raw            Do not neatly format logs
      --since string   Show logs since timestamp (e.g. 2013-01-02T13:23:37) or relative (e.g. 42m for 42 minutes)
      --tail string    Number of lines to show from the end of the logs (default "all")
  -t, --timestamps     Show timestamps

 

Afficher les logs relatifs à un service ou une tâche

docker service logs [OPTIONS] service|task

ex :
Ci-dessous nous créons un service constitué de 6 tâches réparties sur 4 nodes.

$ docker service logs vote
vote.3.m6vav0b3geqf@node1    | [2018-10-29 01:37:21 +0000] [1] [INFO] Starting gunicorn 19.6.0
vote.5.j88qt3ovckgp@node1    | [2018-10-29 01:37:22 +0000] [1] [INFO] Starting gunicorn 19.6.0
vote.1.ogafxdmgkmsn@node1    | [2018-10-29 01:37:22 +0000] [1] [INFO] Starting gunicorn 19.6.0
vote.1.ogafxdmgkmsn@node1    | [2018-10-29 01:37:22 +0000] [1] [INFO] Listening at: http://0.0.0.0:80 (1)
vote.3.m6vav0b3geqf@node1    | [2018-10-29 01:37:21 +0000] [1] [INFO] Listening at: http://0.0.0.0:80 (1)
vote.5.j88qt3ovckgp@node1    | [2018-10-29 01:37:22 +0000] [1] [INFO] Listening at: http://0.0.0.0:80 (1)
vote.5.j88qt3ovckgp@node1    | [2018-10-29 01:37:22 +0000] [1] [INFO] Using worker: sync
vote.1.ogafxdmgkmsn@node1    | [2018-10-29 01:37:22 +0000] [1] [INFO] Using worker: sync
[...]
$ docker service logs ogafxdmgkmsn
vote.1.ogafxdmgkmsn@node1    | [2018-10-29 01:37:22 +0000] [1] [INFO] Starting gunicorn 19.6.0
vote.1.ogafxdmgkmsn@node1    | [2018-10-29 01:37:22 +0000] [1] [INFO] Listening at: http://0.0.0.0:80 (1)
vote.1.ogafxdmgkmsn@node1    | [2018-10-29 01:37:22 +0000] [1] [INFO] Using worker: sync
vote.1.ogafxdmgkmsn@node1    | [2018-10-29 01:37:22 +0000] [11] [INFO] Booting worker with pid: 11
vote.1.ogafxdmgkmsn@node1    | [2018-10-29 01:37:22 +0000] [12] [INFO] Booting worker with pid: 12
vote.1.ogafxdmgkmsn@node1    | [2018-10-29 01:37:22 +0000] [13] [INFO] Booting worker with pid: 13
vote.1.ogafxdmgkmsn@node1    | [2018-10-29 01:37:22 +0000] [14] [INFO] Booting worker with pid: 14

 

Afficher les logs en mode follow (-f)

docker service logs [OPTIONS] -f service|task

 

DOCKER SERVICE LS

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

List services

Aliases:
  ls, list

Options:
  -f, --filter filter   Filter output based on conditions provided
      --format string   Pretty-print services using a Go template
  -q, --quiet           Only display IDs

 

Lister les services

docker service ls [OPTIONS]

ex :

$ docker service ls
ID                  NAME                MODE                REPLICAS            IMAGE                   PORTS
w6oq3h8zshjb        vote                replicated          6/6                 instavote/vote:latest   *:8080->80/tcp
$ docker service ls -f "name=vote"
ID                  NAME                MODE                REPLICAS            IMAGE                   PORTS
w6oq3h8zshjb        vote                replicated          6/6                 instavote/vote:latest   *:8080->80/tcp
$ docker service ls --format "{{.ID}}: {{.Mode}} {{.Replicas}}"
w6oq3h8zshjb: replicated 6/6

 

DOCKER SERVICE PS

Commande : docker service ps
Usage:	docker service ps [OPTIONS] SERVICE [SERVICE...]

List the tasks of one or more services

Options:
  -f, --filter filter   Filter output based on conditions provided
      --format string   Pretty-print tasks using a Go template
      --no-resolve      Do not map IDs to Names
      --no-trunc        Do not truncate output
  -q, --quiet           Only display task IDs

 

Lister les tâches d’un ou plusieurs services

docker service ps [OPTIONS] service [service...]

ex :

$ docker service ps vote
ID                  NAME                IMAGE                   NODE                DESIRED STATE       CURRENT STATE            ERROR               PORTS
u6ft5zbc8xwz        vote.1              instavote/vote:latest   node3               Running             Running 29 seconds ago         
diftv07phzat        vote.2              instavote/vote:latest   node2               Running             Running 27 seconds ago         
k6qtg2kiewxx        vote.3              instavote/vote:latest   node3               Running             Running 29 seconds ago         
9t09sz9pr4e1        vote.4              instavote/vote:latest   node4               Running             Running 28 seconds ago         
g7dbwtofnrmt        vote.5              instavote/vote:latest   node1               Running             Running 26 seconds ago         
m9vthhag9a1o        vote.6              instavote/vote:latest   node2               Running             Running 27 seconds ago

 

DOCKER SERVICE ROLLBACK

Commande : docker service rollback
Usage:	docker service rollback [OPTIONS] SERVICE

Revert changes to a service's configuration

Options:
  -d, --detach   Exit immediately instead of waiting for the service to converge
  -q, --quiet    Suppress progress output

 

Effectuer le rollback d’un service

docker service rollback [OPTIONS] service

Un service mis à jour avec la commande docker service update peut être rétabli dans sa version précédente (Spec -> PreviousSpec) avec la commande docker service rollback.
ex :

$ docker service rollback vote
vote
rollback: manually requested rollback
overall progress: rolling back update: 6 out of 6 tasks
1/6: running   [>                                                  ]
2/6: running   [>                                                  ]
3/6: running   [>                                                  ]
4/6: running   [>                                                  ]
5/6: running   [>                                                  ]
6/6: running   [>                                                  ]
verify: Service converged

 

DOCKER SERVICE SCALE

Commande : docker service scale
Usage:	docker service scale SERVICE=REPLICAS [SERVICE=REPLICAS...]

Scale one or multiple replicated services

Options:
  -d, --detach   Exit immediately instead of waiting for the service to converge

 

Scaler un service répliqué

docker service scale service=N [service=N...]

Equivaut à :
$ docker service update --replicas N service
ex :

$ docker service ls
ID                  NAME                 MODE                REPLICAS            IMAGE                                          PORTS
kn1qdmquzz1r        mystack_db           replicated          1/1                 postgres:9.4
xt2mwakr6u66        mystack_redis        replicated          1/1                 redis:alpine                                   *:30001->6379/tcp
3qi1rdmocngh        mystack_result       replicated          1/1                 dockersamples/examplevotingapp_result:before   *:5001->80/tcp
xehxo13zisbz        mystack_visualizer   replicated          1/1                 dockersamples/visualizer:stable                *:8080->8080/tcp
ryq7lsbz944j        mystack_vote         replicated          2/2                 dockersamples/examplevotingapp_vote:before     *:5000->80/tcp
q2onk7lai1xc        mystack_worker       replicated          1/1                 dockersamples/examplevotingapp_worker:latest
$ docker service scale mystack_db=3
mystack_db scaled to 3
overall progress: 3 out of 3 tasks
1/3: running   [==================================================>]
2/3: running   [==================================================>]
3/3: running   [==================================================>]
verify: Service converged
$ docker service ls
ID                  NAME                 MODE                REPLICAS            IMAGE                                          PORTS
kn1qdmquzz1r        mystack_db           replicated          3/3                 postgres:9.4
xt2mwakr6u66        mystack_redis        replicated          1/1                 redis:alpine                                   *:30001->6379/tcp
3qi1rdmocngh        mystack_result       replicated          1/1                 dockersamples/examplevotingapp_result:before   *:5001->80/tcp
xehxo13zisbz        mystack_visualizer   replicated          1/1                 dockersamples/visualizer:stable                *:8080->8080/tcp
ryq7lsbz944j        mystack_vote         replicated          2/2                 dockersamples/examplevotingapp_vote:before     *:5000->80/tcp
q2onk7lai1xc        mystack_worker       replicated          1/1                 dockersamples/examplevotingapp_worker:latest

 

DOCKER SERVICE UPDATE

Commande : docker service update
Usage:	docker service update [OPTIONS] SERVICE

Update a service

Options:
      --args command                       Service command args
      --config-add config                  Add or update a config file on a service
      --config-rm list                     Remove a configuration file
      --constraint-add list                Add or update a placement constraint
      --constraint-rm list                 Remove a constraint
      --container-label-add list           Add or update a container label
      --container-label-rm list            Remove a container label by its key
      --credential-spec credential-spec    Credential spec for managed service account (Windows only)
  -d, --detach                             Exit immediately instead of waiting for the service to converge
      --dns-add list                       Add or update a custom DNS server
      --dns-option-add list                Add or update a DNS option
      --dns-option-rm list                 Remove a DNS option
      --dns-rm list                        Remove a custom DNS server
      --dns-search-add list                Add or update a custom DNS search domain
      --dns-search-rm list                 Remove a DNS search domain
      --endpoint-mode string               Endpoint mode (vip or dnsrr)
      --entrypoint command                 Overwrite the default ENTRYPOINT of the image
      --env-add list                       Add or update an environment variable
      --env-rm list                        Remove an environment variable
      --force                              Force update even if no changes require it
      --generic-resource-add list          Add a Generic resource
      --generic-resource-rm list           Remove a Generic resource
      --group-add list                     Add an additional supplementary user group to the container
      --group-rm list                      Remove a previously added supplementary user group from the container
      --health-cmd string                  Command to run to check health
      --health-interval duration           Time between running the check (ms|s|m|h)
      --health-retries int                 Consecutive failures needed to report unhealthy
      --health-start-period duration       Start period for the container to initialize before counting retries towards unstable (ms|s|m|h)
      --health-timeout duration            Maximum time to allow one check to run (ms|s|m|h)
      --host-add list                      Add a custom host-to-IP mapping (host:ip)
      --host-rm list                       Remove a custom host-to-IP mapping (host:ip)
      --hostname string                    Container hostname
      --image string                       Service image tag
      --init                               Use an init inside each service container to forward signals and reap processes
      --isolation string                   Service container isolation mode
      --label-add list                     Add or update a service label
      --label-rm list                      Remove a label by its key
      --limit-cpu decimal                  Limit CPUs
      --limit-memory bytes                 Limit Memory
      --log-driver string                  Logging driver for service
      --log-opt list                       Logging driver options
      --mount-add mount                    Add or update a mount on a service
      --mount-rm list                      Remove a mount by its target path
      --network-add network                Add a network
      --network-rm list                    Remove a network
      --no-healthcheck                     Disable any container-specified HEALTHCHECK
      --no-resolve-image                   Do not query the registry to resolve image digest and supported platforms
      --placement-pref-add pref            Add a placement preference
      --placement-pref-rm pref             Remove a placement preference
      --publish-add port                   Add or update a published port
      --publish-rm port                    Remove a published port by its target port
  -q, --quiet                              Suppress progress output
      --read-only                          Mount the container's root filesystem as read only
      --replicas uint                      Number of tasks
      --reserve-cpu decimal                Reserve CPUs
      --reserve-memory bytes               Reserve Memory
      --restart-condition string           Restart when condition is met ("none"|"on-failure"|"any")
      --restart-delay duration             Delay between restart attempts (ns|us|ms|s|m|h)
      --restart-max-attempts uint          Maximum number of restarts before giving up
      --restart-window duration            Window used to evaluate the restart policy (ns|us|ms|s|m|h)
      --rollback                           Rollback to previous specification
      --rollback-delay duration            Delay between task rollbacks (ns|us|ms|s|m|h)
      --rollback-failure-action string     Action on rollback failure ("pause"|"continue")
      --rollback-max-failure-ratio float   Failure rate to tolerate during a rollback
      --rollback-monitor duration          Duration after each task rollback to monitor for failure (ns|us|ms|s|m|h)
      --rollback-order string              Rollback order ("start-first"|"stop-first")
      --rollback-parallelism uint          Maximum number of tasks rolled back simultaneously (0 to roll back all at once)
      --secret-add secret                  Add or update a secret on a service
      --secret-rm list                     Remove a secret
      --stop-grace-period duration         Time to wait before force killing a container (ns|us|ms|s|m|h)
      --stop-signal string                 Signal to stop the container
  -t, --tty                                Allocate a pseudo-TTY
      --update-delay duration              Delay between updates (ns|us|ms|s|m|h)
      --update-failure-action string       Action on update failure ("pause"|"continue"|"rollback")
      --update-max-failure-ratio float     Failure rate to tolerate during an update
      --update-monitor duration            Duration after each task update to monitor for failure (ns|us|ms|s|m|h)
      --update-order string                Update order ("start-first"|"stop-first")
      --update-parallelism uint            Maximum number of tasks updated simultaneously (0 to update all at once)
  -u, --user string                        Username or UID (format: [:])
      --with-registry-auth                 Send registry authentication details to swarm agents
  -w, --workdir string                     Working directory inside the container

 

Paramétrer le délai de mise à jour d’un service sur les nodes

$ docker service update [OPTIONS] --update-parallelism N --update-delay T service

On définit un rolling upgrade qui mettra les tâches à jour N par N toutes les T secondes.

  • --update-parallelism uint : Maximum number of tasks updated simultaneously (0 to update all at once)
  • --update-delay duration : Delay between updates (ns|us|ms|s|m|h)

ex :

$ docker service update --update-parallelism 2 --update-delay 15s vote
vote
overall progress: 6 out of 6 tasks
1/6: running   [==================================================>]
2/6: running   [==================================================>]
3/6: running   [==================================================>]
4/6: running   [==================================================>]
5/6: running   [==================================================>]
6/6: running   [==================================================>]
verify: Service converged

 

Mettre à jour l’image d’un service sur les nodes

$ docker service update [OPTIONS] --image image[:tag] service

ex :

$ docker service update --image instavote/vote:indent vote
vote
overall progress: 6 out of 6 tasks
1/6: running   [==================================================>]
2/6: running   [==================================================>]
3/6: running   [==================================================>]
4/6: running   [==================================================>]
5/6: running   [==================================================>]
6/6: running   [==================================================>]
verify: Service converged

 

Forcer la redistribution des tâches d’un service sur les nodes

$ docker service update --force service

ex :

$ docker service update --force vote_vote
vote_vote
overall progress: 2 out of 2 tasks
1/2: running   [==================================================>]
2/2: running   [==================================================>]
verify: Service converged

 

Scaler un service répliqué

$ docker service update --replicas N service

Equivaut à :
docker service scale service=N
ex :

$ docker service update --replicas 3 vote
vote
overall progress: 3 out of 3 tasks
1/3: running   [==================================================>]
2/3: running   [==================================================>]
3/3: running   [==================================================>]
verify: Service converged

 

Ajouter un secret à un service existant

$ docker service update --secret-add secret_name service

ex :

$ docker service update --secret-add dbuser mydb
mydb
overall progress: 1 out of 1 tasks
1/1: running   [==================================================>]
verify: Service converged

 

Supprimer un secret à un service existant

$ docker service update --secret-rm secret_name service

ex :

$ docker service update --secret-rm dbuser mydb
mydb
overall progress: 1 out of 1 tasks
1/1: running   [==================================================>]
verify: Service converged

 

Ajouter une config à un service existant

$ docker service update --config-add config_name service

ex :

$ docker service update --config-add my-config redis
redis
overall progress: 1 out of 1 tasks
1/1: running   [==================================================>]
verify: Service converged

 

Supprimer une config à un service existant

$ docker service update --config-rm config_name service

ex :

$ docker service update --config-rm my-config redis
redis
overall progress: 1 out of 1 tasks
1/1: running   [==================================================>]
verify: Service converged

 

Modifier le port publié pour un service

$ docker service update --publish-rm old-host-port --publish-add new-host-port:exposed-port service

Le port précédemment publié doit être supprimé en même temps que le nouveau est ajouté.
ex :

$ docker service update --publish-rm 8088 --publish-add 9090:80 mystack_drupal
mystack_drupal
overall progress: 1 out of 1 tasks 
1/1: running   [==================================================>] 
verify: Service converged

 

DOCKER STACK

Commande : docker stack
Usage:	docker stack [OPTIONS] COMMAND

Manage Docker stacks

Options:
      --orchestrator string   Orchestrator to use (swarm|kubernetes|all)

Commands:
  deploy      Deploy a new stack or update an existing stack
  ls          List stacks
  ps          List the tasks in the stack
  rm          Remove one or more stacks
  services    List the services in the stack

Run 'docker stack COMMAND --help' for more information on a command.
[adminsys@dockeros docker]$ docker stack services
"docker stack services" requires exactly 1 argument.
See 'docker stack services --help'.

Usage:  docker stack services [OPTIONS] STACK

List the services in the stack

 

DOCKER STACK DEPLOY

Commande : docker stack deploy

Usage:	docker stack deploy [OPTIONS] STACK

Deploy a new stack or update an existing stack

Aliases:
  deploy, up

Options:
      --bundle-file string     Path to a Distributed Application Bundle file
  -c, --compose-file strings   Path to a Compose file, or "-" to read from stdin
      --orchestrator string    Orchestrator to use (swarm|kubernetes|all)
      --prune                  Prune services that are no longer referenced
      --resolve-image string   Query the registry to resolve image digest and supported platforms ("always"|"changed"|"never") (default "always")
      --with-registry-auth     Send registry authentication details to Swarm agents

 

Déployer une nouvelle stack ou mettre à jour une stack existante à partir d’un fichier Docker Compose

$ docker stack deploy [OPTIONS] -c /path/to/file.yml stack

ex :

$ docker stack deploy -c docker-stack.yml mystack
Creating network mystack_frontend
Creating network mystack_backend
Creating network mystack_default
Creating service mystack_visualizer
Creating service mystack_redis
Creating service mystack_db
Creating service mystack_vote
Creating service mystack_result
Creating service mystack_worker
$ docker stack ls
NAME                SERVICES            ORCHESTRATOR
mystack             6                   Swarm
$ docker service ls
ID                  NAME                 MODE                REPLICAS            IMAGE                                          PORTS
kn1qdmquzz1r        mystack_db           replicated          1/1                 postgres:9.4
xt2mwakr6u66        mystack_redis        replicated          1/1                 redis:alpine                                   *:30001->6379/tcp
3qi1rdmocngh        mystack_result       replicated          1/1                 dockersamples/examplevotingapp_result:before   *:5001->80/tcp
xehxo13zisbz        mystack_visualizer   replicated          1/1                 dockersamples/visualizer:stable                *:8080->8080/tcp
ryq7lsbz944j        mystack_vote         replicated          2/2                 dockersamples/examplevotingapp_vote:before     *:5000->80/tcp
q2onk7lai1xc        mystack_worker       replicated          1/1                 dockersamples/examplevotingapp_worker:latest

 

DOCKER STACK LS

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

List stacks

Aliases:
  ls, list

Options:
      --format string         Pretty-print stacks using a Go template
      --orchestrator string   Orchestrator to use (swarm|kubernetes|all)

 

Lister les stacks déployées

$ docker stack ls [OPTIONS]

ex :

$ docker stack ls
NAME                SERVICES            ORCHESTRATOR
mystack             6                   Swarm

 

DOCKER STACK PS

Commande : docker stack ps
Usage:	docker stack ps [OPTIONS] STACK

List the tasks in the stack

Options:
  -f, --filter filter         Filter output based on conditions provided
      --format string         Pretty-print tasks using a Go template
      --no-resolve            Do not map IDs to Names
      --no-trunc              Do not truncate output
      --orchestrator string   Orchestrator to use (swarm|kubernetes|all)
  -q, --quiet                 Only display task IDs

 

Afficher la liste des tâches d’une stack

$ docker stack ps [OPTIONS] stack

ex :

$ docker stack ps mystack
ID                  NAME                   IMAGE                                          NODE                DESIRED STATE       CURRENT STATE                  ERROR               PORTS
ilwcw8ben8ie        mystack_visualizer.1   dockersamples/visualizer:stable                node1               Running             Preparing about a minute ago
icez0oqcyhqv        mystack_worker.1       dockersamples/examplevotingapp_worker:latest   node1               Running             Preparing 2 minutes ago     
ka9af5qd2jwn        mystack_result.1       dockersamples/examplevotingapp_result:before   node1               Running             Preparing 2 minutes ago     
c4v7zeoqyasd        mystack_vote.1         dockersamples/examplevotingapp_vote:before     node2               Running             Running about a minute ago  
6anuzryrdjxv        mystack_db.1           postgres:9.4                                   node1               Running             Running 49 seconds ago      
fu7hrmsv8lqx        mystack_redis.1        redis:alpine                                   node2               Running             Running about a minute ago  
h981k89na6y8        mystack_vote.2         dockersamples/examplevotingapp_vote:before     node1               Running             Running about a minute ago

 

DOCKER STACK SERVICES

Commande : docker stack services
Usage:	docker stack services [OPTIONS] STACK

List the services in the stack

Options:
  -f, --filter filter         Filter output based on conditions provided
      --format string         Pretty-print services using a Go template
      --orchestrator string   Orchestrator to use (swarm|kubernetes|all)
  -q, --quiet                 Only display IDs

 

Lister les services d’une stack

$ docker stack services [OPTIONS] stack

ex :

$ docker stack services mystack
ID                  NAME                 MODE                REPLICAS            IMAGE                                          PORTS
3qi1rdmocngh        mystack_result       replicated          1/1                 dockersamples/examplevotingapp_result:before   *:5001->80/tcp
kn1qdmquzz1r        mystack_db           replicated          3/3                 postgres:9.4
q2onk7lai1xc        mystack_worker       replicated          1/1                 dockersamples/examplevotingapp_worker:latest
ryq7lsbz944j        mystack_vote         replicated          2/2                 dockersamples/examplevotingapp_vote:before     *:5000->80/tcp
xehxo13zisbz        mystack_visualizer   replicated          1/1                 dockersamples/visualizer:stable                *:8080->8080/tcp
xt2mwakr6u66        mystack_redis        replicated          1/1                 redis:alpine                                   *:30001->6379/tcp

 

DOCKER STACK RM

Commande : docker stack rm
Usage:	docker stack rm [OPTIONS] STACK [STACK...]

Remove one or more stacks

Aliases:
  rm, remove, down

Options:
      --orchestrator string   Orchestrator to use (swarm|kubernetes|all)

 

Supprimer une ou plusieurs stacks

$ docker stack rm [OPTIONS] stack [stack...]

ex :

$ docker stack rm mystack
Removing service mystack_db
Removing service mystack_redis
Removing service mystack_result
Removing service mystack_visualizer
Removing service mystack_vote
Removing service mystack_worker
Removing network mystack_frontend
Removing network mystack_backend
Removing network mystack_default

 

DOCKER SWARM

Commande : docker swarm
Usage:	docker swarm COMMAND

Manage Swarm

Commands:
  ca          Display and rotate the root CA
  init        Initialize a swarm
  join        Join a swarm as a node and/or manager
  join-token  Manage join tokens
  leave       Leave the swarm
  unlock      Unlock swarm
  unlock-key  Manage the unlock key
  update      Update the swarm

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

 

DOCKER SWARM INIT

Commande : docker swarm init
Usage:	docker swarm init [OPTIONS]

Initialize a swarm

Options:
      --advertise-addr string           Advertised address (format: [:port])
      --autolock                        Enable manager autolocking (requiring an unlock key to start a stopped manager)
      --availability string             Availability of the node ("active"|"pause"|"drain") (default "active")
      --cert-expiry duration            Validity period for node certificates (ns|us|ms|s|m|h) (default 2160h0m0s)
      --data-path-addr string           Address or interface to use for data path traffic (format: )
      --dispatcher-heartbeat duration   Dispatcher heartbeat period (ns|us|ms|s|m|h) (default 5s)
      --external-ca external-ca         Specifications of one or more certificate signing endpoints
      --force-new-cluster               Force create a new cluster from current state
      --listen-addr node-addr           Listen address (format: [:port]) (default 0.0.0.0:2377)
      --max-snapshots uint              Number of additional Raft snapshots to retain
      --snapshot-interval uint          Number of log entries between Raft snapshots (default 10000)
      --task-history-limit int          Task history retention limit (default 5)

 

Initialiser un swarm (Manager Status : -> Leader)

docker swarm init --advertise-addr ip-addr

L’option --advertise-addr spécifie l’interface réseau utilisée pour que le leader soit accessible par les autres nodes du swarm. Cette option est obligatoire s’il y a plusieurs interfaces réseaux sur le leader.
Une fois le swarm initialisé, le node à l’origine de l’initialisation est leader du swarm.
ex :

$ docker swarm init --advertise-addr 192.168.99.105
Swarm initialized: current node (2tbkss0ywais935a56ejcsaj3) is now a manager.

To add a worker to this swarm, run the following command:

    docker swarm join --token SWMTKN-1-5gatiua1ou132p34xcd1ono2j88emxbwhy4uzvz1hodj0c1pi3-5bdfn48wm5hpiw5644rmnwhzk 192.168.99.105:2377

To add a manager to this swarm, run 'docker swarm join-token manager' and follow the instructions.

$ docker node ls
ID                            HOSTNAME            STATUS              AVAILABILITY        MANAGER STATUS      ENGINE VERSION
2tbkss0ywais935a56ejcsaj3 *   node1               Ready               Active              Leader              18.06.1-ce
$ docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
32841544151c        bridge              bridge              local
32acdfbbac20        docker_gwbridge     bridge              local
6af2dc2c4d7c        host                host                local
xpyxo8tirhe0        ingress             overlay             swarm
b6de6c7f9a85        none                null                local

Les réseaux bridge, host et none sont les réseaux par défaut, hors swarm, créés à l’installation du démon Docker.
Les réseaux ingress (connectivité depuis l’extérieur et routing mesh) et docker_gwbridge (connectivité vers l’extérieur) sont créés sur l’hôte à l’initialisation du cluster swarm.
 

Réinitialiser un swarm

docker swarm init --force-new-cluster --advertise-addr ip-addr

Force la création d’un nouveau cluster à partir de l’état courant.
Le contenu du dossier /var/lib/docker/swarm (dossier des logs et clefs du swarm) est maintenu en l’état, il n’est donc pas réinitialisé.
ex :

$ docker swarm init --force-new-cluster --advertise-addr 192.168.99.105

 

DOCKER SWARM JOIN

Commande : docker swarm join
Usage:	docker swarm join [OPTIONS] HOST:PORT

Join a swarm as a node and/or manager

Options:
      --advertise-addr string   Advertised address (format: [:port])
      --availability string     Availability of the node ("active"|"pause"|"drain") (default "active")
      --data-path-addr string   Address or interface to use for data path traffic (format: )
      --listen-addr node-addr   Listen address (format: [:port]) (default 0.0.0.0:2377)
      --token string            Token for entry into the swarm

 

Rejoindre un swarm en tant que worker ou manager depuis un node

$ docker swarm join --token token ip-addr

L’adresse IP est celle du leader utilisée lors de l’initialisation du swarm.
Le token est fourni sur le leader au même moment pour le rattachement d’un worker.
Le token de jonction au swarm pour un manager nécessite la commande docker swarm join-token manager.
Le token généré est différent pour un worker et pour un manager.
Il est conseillé d’avoir un nombre impair de managers avec un minimum de 3.
ex :

$ docker swarm join --token SWMTKN-1-5gatiua1ou132p34xcd1ono2j88emxbwhy4uzvz1hodj0c1pi3-5bdfn48wm5hpiw5644rmnwhzk 192.168.99.105:2377
This node joined a swarm as a worker.
$ docker swarm join --token SWMTKN-1-11rra7zaiofruwfo8yggmhxpuu9rcoborgs4hccxbkivrli83j-5bcw6y5t5ctbhqj72x08a7ehq 192.168.99.102:2377
This node joined a swarm as a manager.

Il est conseillé d’avoir un nombre impair de managers avec un minimum de 3.
Depuis le leader on peut vérifier les membres du swarm :

$ docker node ls
ID                            HOSTNAME            STATUS              AVAILABILITY        MANAGER STATUS      ENGINE VERSION
40ybct29ekka2s7za3zjm4eig *   node1               Ready               Active              Leader              18.06.1-ce
kqx2im30a07l8dewuim7cm515     node2               Ready               Active                                  18.06.1-ce
k30xuj35b2p4n9ng6jt82tuyw     node3               Ready               Active                                  18.06.1-ce
nzm7c002yh9ky9pchsw9xsyvy     node4               Ready               Active              Reachable           18.06.1-ce

 

DOCKER SWARM JOIN-TOKEN

Commande : docker swarm join-token
Usage:	docker swarm join-token [OPTIONS] (worker|manager)

Manage join tokens

Options:
  -q, --quiet    Only display token
      --rotate   Rotate join token

 

Générer un token sur le leader pour la jonction d’un node au swarm en tant que worker

$ docker swarm join-token worker

ex :

$ docker swarm join-token worker
To add a worker to this swarm, run the following command:

    docker swarm join --token SWMTKN-1-5gatiua1ou132p34xcd1ono2j88emxbwhy4uzvz1hodj0c1pi3-5bdfn48wm5hpiw5644rmnwhzk 192.168.99.105:2377

 

Générer un token sur le leader pour la jonction d’un node au swarm en tant que manager

$ docker swarm join-token manager

Il est conseillé d’avoir un nombre impair de managers avec un minimum de 3.
ex :

$ docker swarm join-token manager
To add a manager to this swarm, run the following command:

    docker swarm join --token SWMTKN-1-5gatiua1ou132p34xcd1ono2j88emxbwhy4uzvz1hodj0c1pi3-8ugl7xra99r5dv1use5867kau 192.168.99.105:2377

 

DOCKER SWARM LEAVE

Commande : docker swarm leave
Usage:	docker swarm leave [OPTIONS]

Leave the swarm

Options:
  -f, --force   Force this node to leave the swarm, ignoring warnings

 

Quitter un cluster swarm

$ docker swarm leave [OPTIONS]

S’il s’agit d’un manager, il doit être destitué au préalable (docker node demote).
ex :

$ docker swarm leave
Node left the swarm.

 

REFERENCES

Fermer le menu
%d blogueurs aiment cette page :