您的当前位置:首页Docker系列之十:docker service命令详解

Docker系列之十:docker service命令详解

2024-12-14 来源:哗拓教育

title: Docker系列之:Docker系列之十:docker service命令详解
categories: Docker
tags:
- Docker
timezone: Asia/Shanghai
date: 2019-02-19


基本概念

节点

运行 Docker 的主机可以主动初始化一个 Swarm 集群或者加入一个已存在的 Swarm 集群,这样这个运行 Docker 的主机就成为一个 Swarm 集群的节点 (node) 。

  • 节点分为管理 (manager) 节点和工作 (worker) 节点。

管理节点用于 Swarm 集群的管理,docker swarm 命令基本只能在管理节点执行(节点退出集群命令 docker swarm leave 可以在工作节点执行)。一个 Swarm 集群可以有多个管理节点,但只有一个管理节点可以成为 leader,leader 通过 raft 协议实现。

  • 工作节点是任务执行节点,管理节点将服务 (service)

下发至工作节点执行。管理节点默认也作为工作节点。你也可以通过配置让服务只运行在管理节点。

服务和任务

  • 任务 (Task)是 Swarm 中的最小的调度单位,目前来说就是一个单一的容器。

  • 服务 (Services) 是指一组任务的集合,服务定义了任务的属性。服务有两种模式:

replicated services 按照一定规则在各个工作节点上运行指定个数的任务。

global services 每个工作节点上运行一个任务

两种模式通过 docker service create 的 --mode 参数指定。

环境

[root@centos181001 nginx]# cat /etc/centos-release
CentOS Linux release 7.6.1810 (Core) 

[root@centos181001 nginx]# docker -v 
Docker version 18.09.1, build 4c52b90

常用命令示例

启动服务
docker service create nginx
docker service create -p 80:80 nginx
docker service create --replicas 5 nginx

停止某个服务并删除
docker service rm xenodochial_ritchie

查看已经在运行的服务
docker service ls

查看某个服务运行状态
docker service ps agitated_archimedes

增加和删除DNS
docker service update --dns-add 222.222.222.222 tender_hofstadter
docker service update --dns-rm 222.222.222.222 tender_hofstadter

增加和删除端口映射
docker service update --publish-add 80:80 xenodochial_ritchie
docker service update --publish-rm 80:80 xenodochial_ritchie

缩容和扩容
docker service scale tender_hofstadter=2
docker service scale tender_hofstadter=5

docker service命令详解

[root@centos181001 nginx]# docker service --help

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.

create选项:创建一个新的服务

[root@centos181001 ~]# docker service create --help

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

      --dns-option list                    Set DNS options
                                            设置DNS选项

      --dns-search list                    Set custom DNS search domains
                                            设置DNS搜索域

      --endpoint-mode string               Endpoint mode (vip or dnsrr) (default "vip")
                                            端点模式 (vip or dnsrr) (default "vip")

      --entrypoint command                 Overwrite the default ENTRYPOINT of the image
                                            覆盖镜像的默认ENTRYPOINT

  -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)
                                            健康检查间隔 (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)
                                            在重试计数到不稳定之前,开始容器初始化的时间段(ms|s|m|h)

      --health-timeout duration            Maximum time to allow one check to run (ms|s|m|h)
                                            允许一次健康检查最长运行时间 (ms|s|m|h)

      --host list                          Set one or more custom host-to-IP mappings (host:ip)
                                            设置一个或多个自定义主机到IP映射 (host:ip)

      --hostname string                    Container hostname
                                            容器名称

      --init                               Use an init inside each service container to forward signals and reap processes
                                            在每个服务容器中使用init来转发信号并收集进程

      --isolation string                   Service container isolation mode
                                            服务容器隔离模式

  -l, --label list                         Service labels
                                            服务标签
      --limit-cpu decimal                  Limit CPUs
                                            CPU限制

      --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
                                            为本服务需要预留的CPU资源

      --reserve-memory bytes               Reserve Memory
                                            为本服务需要预留的内存资源

      --restart-condition string           Restart when condition is met ("none"|"on-failure"|"any") (default "any")
                                            满足条件时重新启动("none"|"on-failure"|"any") (default "any")

      --restart-delay duration             Delay between restart attempts (ns|us|ms|s|m|h) (default 5s)
                                            重启尝试之间的延迟 (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)
                                            任务回滚之间的延迟(ns|us|ms|s|m|h) (default 0s)

      --rollback-failure-action string     Action on rollback failure ("pause"|"continue") (default "pause")
                                            回滚失败的操作("pause"|"continue") (default "pause")

      --rollback-max-failure-ratio float   Failure rate to tolerate during a rollback (default 0)
                                            回滚期间容忍的失败率(default 0)

      --rollback-monitor duration          Duration after each task rollback to monitor for failure (ns|us|ms|s|m|h) (default 5s)
                                            每次任务回滚后监视失败的持续时间 (ns|us|ms|s|m|h) (default 5s)

      --rollback-order string              Rollback order ("start-first"|"stop-first") (default "stop-first")
                                            回滚选项("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)
                                            同时回滚的最大任务数(0表示一次回滚)(默认值为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)
                                            在强行杀死容器之前等待的时间(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)
                                            更新之间的延迟(ns|us|ms|s|m|h) (default 0s)

      --update-failure-action string       Action on update failure ("pause"|"continue"|"rollback") (default "pause")
                                            更新失败后选项("pause"|"continue"|"rollback") (default "pause")
      --update-max-failure-ratio float     Failure rate to tolerate during an update (default 0)
                                            更新期间容忍的故障率(默认为0)

      --update-monitor duration            Duration after each task update to monitor for failure (ns|us|ms|s|m|h) (default 5s)
                                            每次更新任务后监视失败的持续时间(ns | us | ms | s | m | h)(默认为5s)

      --update-order string                Update order ("start-first"|"stop-first") (default "stop-first")
                                            更新选项 ("start-first"|"stop-first") (default "stop-first")

      --update-parallelism uint            Maximum number of tasks updated simultaneously (0 to update all at once) (default 1)
                                            同时更新的最大任务数(0表示一次更新所有任务)(默认值为1)

  -u, --user string                        Username or UID (format: <name|uid>[:<group|gid>])
      --with-registry-auth                 Send registry authentication details to swarm agents
                                            将注册表验证详细信息发送给swarm代理

  -w, --workdir string                     Working directory inside the container
                                            指定容器内工作目录(workdir)

inspect选项 - 显示一个或多个服务的详细信息

[root@centos181001 nginx]# docker service inspect --help

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
                        使用给定的Go模板格式化输出

      --pretty          Print the information in a human friendly format
                        以人性化的格式打印信息

logs选项 - 获取服务或任务的日志

[root@centos181001 nginx]# docker service logs --help

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
                        持续输出日志,相当于``tail -f``

      --no-resolve     Do not map IDs to Names in output
                        不要将容器名称输出到日志,而使用CONTAINER ID

      --no-task-ids    Do not include task IDs in output
                        不要将task ID输出到日志

      --no-trunc       Do not truncate output
                        不要截断输出

      --raw            Do not neatly format logs
                        不要整齐地格式化日志(会将前边的容器ID信息等去掉,只保留原始日志内容)

      --since string   Show logs since timestamp (e.g. 2013-01-02T13:23:37) or relative (e.g. 42m for 42 minutes)
                        显示自时间戳(例如2013-01-02T13:23:37)或相对(例如42分钟42分钟)以来的日志

      --tail string    Number of lines to show from the end of the logs (default "all")
                        从日志末尾显示的行数(默认为“全部”)

  -t, --timestamps     Show timestamps
                        显示时间戳

ls选项 - 列出服务

[root@centos181001 nginx]# docker service ls --help

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
                        使用Go模板的漂亮打印服务

  -q, --quiet           Only display IDs
                        只显示服务ID

ps选项 - 列出一个或多个服务\tasks

[root@centos181001 nginx]# docker service ps --help

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
                        使用Go模板的漂亮打印任务

      --no-resolve      Do not map IDs to Names
                        服务名和node名称不要显示名字,而显示ID

      --no-trunc        Do not truncate output
                        不要截断输出

  -q, --quiet           Only display task IDs
                        只输出task ID

rm选项 - 删除一个或多个服务

警告:与docker rm不同,此命令在删除正在运行的服务之前不要求确认。

[root@centos181001 nginx]# docker service rm --help

Usage:  docker service rm SERVICE [SERVICE...]

Remove one or more services

Aliases:
  rm, remove

rollback选项 - 回滚服务

[root@centos181001 nginx]# docker service rollback --help

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
                    抑制进度输出

scale选项 - 缩容或者扩容服务

[root@centos181001 nginx]# docker service scale --help

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
                    立即退出而不是等待服务收敛

    示例:
    docker service scale tender_hofstadter=2

update选项 - 更新一个服务

详解:

[root@centos181001 nginx]# docker service update --help

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

      --dns-option-add list                Add or update a DNS option
                                            添加或更新DNS选项

      --dns-option-rm list                 Remove a DNS option
                                            删除一个DNS选项

      --dns-rm list                        Remove a custom DNS server
                                            删除一个自定义DNS

      --dns-search-add list                Add or update a custom DNS search domain
                                            添加或更新自定义DNS搜索域

      --dns-search-rm list                 Remove a DNS search domain
                                            删除一个自定义DNS搜索域

      --endpoint-mode string               Endpoint mode (vip or dnsrr)
                                            端点模式(vip或dnsrr)

      --entrypoint command                 Overwrite the default ENTRYPOINT of the image
                                            覆盖图像的默认ENTRYPOINT

      --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
                                            定义服务image和标签

      --init                               Use an init inside each service container to forward signals and reap processes
                                            在每个服务容器中使用init来转发信号并收集进程

      --isolation string                   Service container isolation mode
                                            服务容器隔离模式

      --label-add list                     Add or update a service label
                                            添加或更新service标签

      --label-rm list                      Remove a label by its key
                                            删除service标签

      --limit-cpu decimal                  Limit CPUs
                                            CPU限制

      --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)
                                            任务回滚之间的延迟(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)
                                            每次任务回滚后监视失败的持续时间(ns | us | ms | s | m | h)

      --rollback-order string              Rollback order ("start-first"|"stop-first")
                                            回滚顺序(“start-first”|“stop-first”)

      --rollback-parallelism uint          Maximum number of tasks rolled back simultaneously (0 to roll back all at once)
                                            同时回滚的最大任务数(0表示一次回滚)

      --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)
                                            在强制杀死容器之前等待的时间(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)
                                            同时更新的最大任务数(0表示一次更新所有任务)

  -u, --user string                        Username or UID (format: <name|uid>[:<group|gid>])
      --with-registry-auth                 Send registry authentication details to swarm agents
                                            将注册表验证详细信息发送给swarm代理

  -w, --workdir string                     Working directory inside the container
                                            定义容器内的workdir
显示全文