基本概念
節點
運行 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