Docker-Swarm 初探
作者:elfin 資料來源:遇見狂神說
1、環境准備
Docker Swarm是docker三劍客之一,Swarm 是 Docker 原生的集群搭建項目,同時也是最簡單,最易學,最節省資源的,比較適合中小型公司使用。更多性能介紹可以參考純潔的微笑。簡易學習教程可以參考菜鳥教程。
Swarm本身很簡單,但是在學習集群的過程中,你怎么能可以幾台機子用於測試呢,偽分布式?額,算了吧,阿里雲4台機子0.8元/h,難道不香嗎?
1.1 購買實例
這里我們在阿里雲上購買4台機子用於說明,選擇按量付費模式,用后及時銷毀,畢竟家境貧寒!下面介紹操作步驟,阿里雲界面可能會調整,但是大差不差,步驟總是問題不大。
服務器購買頁面:
A(百度:阿里雲,進入官網) --> B(登錄並進入控制台) --> C(左側側邊欄:雲服務器ECS) --> D(我的資源:創建實例或創建我的ECS);
購買需要的服務器:
A(創建我的ECS) --> B(按量付費、選擇離你近的區域、分類:共享型1核2G、4台、選擇鏡像:centos7) --> C(進入下一步,調整帶寬,其他默認即可,下一步) --> D(自定義密碼、自定義實例名,下一步) --> E(下一步確認訂單:確認好基本信息即可購買)
1.2 連接服務器
1.2.1 連接4台服務器
使用xshell連接你剛剛購買的服務器,恰好,xshell免費版的支持四個窗口,對於家境貧寒的我們簡直不要太耐撕。
在終端內右鍵選擇將命令輸入到其他窗口!這里是為了統一安裝環境,總不能咱一個個安裝吧!
檢查每個服務器都安裝好了,下面進入docker安裝環節…
1.2.2 安裝docker
docker的安裝可參考官方教程。
安裝步驟:
-
確保環境是centos7及以上版本,這里買服務器時就選擇了!
-
yum安裝gcc相關環境,需要確保虛擬機可以上外網
$ yum -y install gcc $ yum -y install gcc-c++
-
卸載舊版本
$ sudo yum remove docker \ docker-client \ docker-client-latest \ docker-common \ docker-latest \ docker-latest-logrotate \ docker-logrotate \ docker-engine
-
安裝依賴、設置鏡像倉庫
$ sudo yum install -y yum-utils $ sudo yum-config-manager \ --add-repo \ https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
-
更新yum軟件包索引
$ yum makecache fast
-
安裝Docker-ce
$ sudo yum install docker-ce docker-ce-cli containerd.io
-
啟動Docker
$ systemctl start docker
-
測試命令
$ docker version $ docker run hello-world $ docker images
-
配置鏡像加速
$ sudo mkdir -p /etc/docker $ sudo tee /etc/docker/daemon.json <<-'EOF' { "registry-mirrors": ["https://qiyb9988.mirror.aliyuncs.com"] } EOF $ sudo systemctl daemon-reload $ sudo systemctl restart docker
這里注意json文件格式的正確,直接復制會出錯!
2、工作模式
官方的工作模式介紹
Docker Engine 1.12引入了swarm模式,使您能夠創建一個由一個或多個Docker引擎組成的集群,稱為swarm。swarm由一個或多個節點組成:在swarm模式下運行Docker Engine 1.12或更高版本的物理或虛擬機。
有兩種類型的節點:managers和workers。
worker是不能操作managers的!主節點不能只有一個,也不能使用兩個!至少使用3個。
3、集群搭建
3.1 查看當前的docker環境
[root@iZ2vcf0atudng87wzoeelcZ ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
[root@iZ2vcf0atudng87wzoeelcZ ~]# docker network ls
NETWORK ID NAME DRIVER SCOPE
f555f5076970 bridge bridge local
cf030c9a10db host host local
f6484ff6e7c6 none null local
3.2 查看docker swarm的命令
[root@iZ2vcf0atudng87wzoeelcZ ~]# docker swarm --help
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.
3.3 查看docker swarm init的命令
[root@iZ2vcf0atudng87wzoeelcZ ~]# docker swarm init --help
Usage: docker swarm init [OPTIONS]
Initialize a swarm
Options:
--advertise-addr string Advertised address (format: <ip|interface>[: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: <ip|interface>)
--data-path-port uint32 Port number to use for data path traffic (1024 - 49151). If no value is set
or is set to 0, the default port (4789) is used.
--default-addr-pool ipNetSlice default address pool in CIDR format (default [])
--default-addr-pool-mask-length uint32 default address pool subnet mask length (default 24)
--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: <ip|interface>[: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)
--advertise-addr 必須要配置!
查看服務器elfin04的地址(內網):
[root@iZ2vcf0atudng87wzoeelcZ ~]# ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
link/ether 00:16:3e:01:51:0d brd ff:ff:ff:ff:ff:ff
inet 172.28.58.219/20 brd 172.28.63.255 scope global dynamic eth0
valid_lft 315358385sec preferred_lft 315358385sec
inet6 fe80::216:3eff:fe01:510d/64 scope link
valid_lft forever preferred_lft forever
3: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default
link/ether 02:42:de:7a:76:d8 brd ff:ff:ff:ff:ff:ff
inet 172.17.0.1/16 brd 172.17.255.255 scope global docker0
valid_lft forever preferred_lft forever
當前服務器的地址為172.28.58.219
3.4 創建主節點
[root@iZ2vcf0atudng87wzoeelcZ ~]# docker swarm init --advertise-addr 172.28.58.219
Swarm initialized: current node (xron1grqswlita8xrcwr2d3y5) is now a manager.
To add a worker to this swarm, run the following command:
docker swarm join --token SWMTKN-1-4gb44r3ekdejhtdp0fzc1o3dqdplrobqnjgaojtaghgpdaqjkx-9jl64hbbhul3th0b6jjf6ikji 172.28.58.219:2377
To add a manager to this swarm, run 'docker swarm join-token manager' and follow the instructions.
上面的信息表明,當前節點是一個manager節點,添加工作節點的命令為:docker swarm join --token SWMTKN-1-4gb44r3ekdejhtdp0fzc1o3dqdplrobqnjgaojtaghgpdaqjkx-9jl64hbbhul3th0b6jjf6ikji 172.28.58.219:2377,注意這里的token相當於認證!最后一行說明了如何添加管理節點。
3.5 從節點加入主節點
在3.4中創建主節點時生成了兩個令牌:
# 將其他服務器直接加入當前的主節點
docker swarm join --token SWMTKN-1-4gb44r3ekdejhtdp0fzc1o3dqdplrobqnjgaojtaghgpdaqjkx-9jl64hbbhul3th0b6jjf6ikji 172.28.58.219:2377
# 生成其他主節點的令牌命令(在當前主節點生成后復制到其他服務器使用)
docker swarm join-token manager
# 生成其他從節點的命令
docker swarm join-token worker
現在讓elfin03加入elfin04這個主節點
[root@iZ2vcf0atudng87wzoeelbZ ~]# docker swarm join --token SWMTKN-1-4gb44r3ekdejhtdp0fzc1o3dqdplrobqnjgaojtaghgpdaqjkx-9jl64hbbhul3th0b6jjf6ikji 172.28.58.219:2377
This node joined a swarm as a worker.
現在elfin03通過上面的命令加入了主節點!
查看當前的節點信息:
# elfin04主節點中執行
[root@iZ2vcf0atudng87wzoeelcZ ~]# docker node ls
ID HOSTNAME STATUS AVAILABILITY MANAGER STATUS ENGINE VERSION
llqvxni8acep3zx2s93s6kexx iZ2vcf0atudng87wzoeelbZ Ready Active 20.10.0
xron1grqswlita8xrcwr2d3y5 * iZ2vcf0atudng87wzoeelcZ Ready Active Leader 20.10.0
可以發現有兩個節點,Leader即為我們的elfin04主節點(觀察HOSTNAME)!
生成其他worker加入的令牌:
docker swarm join --token SWMTKN-1-4gb44r3ekdejhtdp0fzc1o3dqdplrobqnjgaojtaghgpdaqjkx-9jl64hbbhul3th0b6jjf6ikji 172.28.58.219:2377
當前的令牌和init時生成的是一樣的!
讓elfin02加入elfin04主節點
# 在elfin02中執行
[root@iZ2vcf0atudng87wzoeelaZ ~]# docker swarm join --token SWMTKN-1-4gb44r3ekdejhtdp0fzc1o3dqdplrobqnjgaojtaghgpdaqjkx-9jl64hbbhul3th0b6jjf6ikji 172.28.58.219:2377
This node joined a swarm as a worker.
# 在elfin04中執行
[root@iZ2vcf0atudng87wzoeelcZ ~]# docker node ls
ID HOSTNAME STATUS AVAILABILITY MANAGER STATUS ENGINE VERSION
flxmp7ppfmd6vadxn8q6hx0ch iZ2vcf0atudng87wzoeelaZ Ready Active 20.10.0
llqvxni8acep3zx2s93s6kexx iZ2vcf0atudng87wzoeelbZ Ready Active 20.10.0
xron1grqswlita8xrcwr2d3y5 * iZ2vcf0atudng87wzoeelcZ Ready Active Leader 20.10.0
iZ2vcf0atudng87wzoeelaZ表明elfin02加入了集群!
3.6 創建其他manager節點
# 在elfin04中執行
[root@iZ2vcf0atudng87wzoeelcZ ~]# docker swarm join-token manager
To add a manager to this swarm, run the following command:
docker swarm join --token SWMTKN-1-4gb44r3ekdejhtdp0fzc1o3dqdplrobqnjgaojtaghgpdaqjkx-32usnk3wlcpe9jn3nylwngd35 172.28.58.219:2377
將elfin01加入elfin04所在集群,且作為一個主節點:
# 在elfin01中執行
[root@iZ2vcf0atudng87wzoeel9Z ~]# docker swarm join --token SWMTKN-1-4gb44r3ekdejhtdp0fzc1o3dqdplrobqnjgaojtaghgpdaqjkx-32usnk3wlcpe9jn3nylwngd35 172.28.58.219:2377
This node joined a swarm as a manager.
[root@iZ2vcf0atudng87wzoeel9Z ~]# docker node ls
ID HOSTNAME STATUS AVAILABILITY MANAGER STATUS ENGINE VERSION
s7negfbauav9sgwsgggr1vj75 * iZ2vcf0atudng87wzoeel9Z Ready Active Reachable 20.10.0
flxmp7ppfmd6vadxn8q6hx0ch iZ2vcf0atudng87wzoeelaZ Ready Active 20.10.0
llqvxni8acep3zx2s93s6kexx iZ2vcf0atudng87wzoeelbZ Ready Active 20.10.0
xron1grqswlita8xrcwr2d3y5 iZ2vcf0atudng87wzoeelcZ Ready Active Leader 20.10.0
注意,docker node ls
要在主節點中執行,而 elfin01 也是主節點,但是我們觀察到TD后面有星號,manager status也是Reachable!星號標識了當前處於哪個主節點,Leader你可以理解為管理節點中的大哥,如果大哥掛了,其他主節點會順位成為大哥,嗯,整的像黑社會似的。
3.7 集群的leave
實驗
停止elfin04中的docker,在elfin01中測試docker node ls
# elfin04
[root@iZ2vcf0atudng87wzoeelcZ ~]# systemctl stop docker
Warning: Stopping docker.service, but it can still be activated by:
docker.socket
# elfin01
[root@iZ2vcf0atudng87wzoeel9Z ~]# docker node ls
Error response from daemon: rpc error: code = Unknown desc = The swarm does not have a leader. It's possible that too few managers are online. Make sure more than half of the managers are online.
上面的結果說明現在集群沒有Leader了,這是為什么呢,elfin01不是應該上位嗎?這里要注意要滿足Raft協議。
恢復elfin04查看變化
# elfin04
[root@iZ2vcf0atudng87wzoeelcZ ~]# systemctl start docker
[root@iZ2vcf0atudng87wzoeelcZ ~]# docker node ls
ID HOSTNAME STATUS AVAILABILITY MANAGER STATUS ENGINE VERSION
s7negfbauav9sgwsgggr1vj75 iZ2vcf0atudng87wzoeel9Z Ready Active Leader 20.10.0
flxmp7ppfmd6vadxn8q6hx0ch iZ2vcf0atudng87wzoeelaZ Ready Active 20.10.0
llqvxni8acep3zx2s93s6kexx iZ2vcf0atudng87wzoeelbZ Ready Active 20.10.0
xron1grqswlita8xrcwr2d3y5 * iZ2vcf0atudng87wzoeelcZ Ready Active Reachable 20.10.0
現在您可以發現elfin04進去集群了,但是它已經不當大哥好多年!變成Reachable的管理節點了。
現在讓elfin03離開集群
[root@iZ2vcf0atudng87wzoeelbZ ~]# docker swarm leave
Node left the swarm.
# elfin04
[root@iZ2vcf0atudng87wzoeelcZ ~]# docker node ls
ID HOSTNAME STATUS AVAILABILITY MANAGER STATUS ENGINE VERSION
s7negfbauav9sgwsgggr1vj75 iZ2vcf0atudng87wzoeel9Z Ready Active Leader 20.10.0
flxmp7ppfmd6vadxn8q6hx0ch iZ2vcf0atudng87wzoeelaZ Ready Active 20.10.0
llqvxni8acep3zx2s93s6kexx iZ2vcf0atudng87wzoeelbZ Down Active 20.10.0
xron1grqswlita8xrcwr2d3y5 * iZ2vcf0atudng87wzoeelcZ Ready Active Reachable 20.10.0
可以看見status變為Down了!
3.8 生成三個manager
# elfin04
[root@iZ2vcf0atudng87wzoeelcZ ~]# docker swarm join-token manager
To add a manager to this swarm, run the following command:
docker swarm join --token SWMTKN-1-4gb44r3ekdejhtdp0fzc1o3dqdplrobqnjgaojtaghgpdaqjkx-32usnk3wlcpe9jn3nylwngd35 172.28.58.219:2377
# elfin03
[root@iZ2vcf0atudng87wzoeelbZ ~]# docker swarm join --token SWMTKN-1-4gb44r3ekdejhtdp0fzc1o3dqdplrobqnjgaojtaghgpdaqjkx-32usnk3wlcpe9jn3nylwngd35 172.28.58.219:2377
This node joined a swarm as a manager.
[root@iZ2vcf0atudng87wzoeelbZ ~]# docker node ls
ID HOSTNAME STATUS AVAILABILITY MANAGER STATUS ENGINE VERSION
s7negfbauav9sgwsgggr1vj75 iZ2vcf0atudng87wzoeel9Z Ready Active Leader 20.10.0
flxmp7ppfmd6vadxn8q6hx0ch iZ2vcf0atudng87wzoeelaZ Ready Active 20.10.0
llqvxni8acep3zx2s93s6kexx iZ2vcf0atudng87wzoeelbZ Down Active 20.10.0
u44zzj5jetxxetkblnx75qr82 * iZ2vcf0atudng87wzoeelbZ Ready Active Reachable 20.10.0
xron1grqswlita8xrcwr2d3y5 iZ2vcf0atudng87wzoeelcZ Ready Active Reachable 20.10.0
# 當前有三個主節點了!顯示elfin03 Down了我們不用管……
注意:此時我停止Leader,在其他主節點使用docker node ls
,效果如下:
[root@iZ2vcf0atudng87wzoeelbZ ~]# docker node ls
ID HOSTNAME STATUS AVAILABILITY MANAGER STATUS ENGINE VERSION
s7negfbauav9sgwsgggr1vj75 iZ2vcf0atudng87wzoeel9Z Down Active Unreachable 20.10.0
flxmp7ppfmd6vadxn8q6hx0ch iZ2vcf0atudng87wzoeelaZ Ready Active 20.10.0
llqvxni8acep3zx2s93s6kexx iZ2vcf0atudng87wzoeelbZ Down Active 20.10.0
u44zzj5jetxxetkblnx75qr82 * iZ2vcf0atudng87wzoeelbZ Ready Active Leader 20.10.0
xron1grqswlita8xrcwr2d3y5 iZ2vcf0atudng87wzoeelcZ Ready Active Reachable 20.10.0
明顯elfin01顯示Unreachable了,而此時小弟elfin03上位成功了,終於熬成Leader了!
此時是符合Raft協議的,即我們要滿足大多數原則,只有兩個主節點,壞一個就只有一個,就不能滿足大多數!所以集群至少要有兩個主節點。
3.9 小節
- 生成主節點
- 加入(管理者manager、worker)
- work就是工作的,manager就是管理的!
將主節點全部啟動起來。使集群正常……
4、集群應用部署
這一節我們主要是體驗彈性、擴縮容。以后就不要使用docker run進行啟動部署了,當然docker-compose up也不適合你,一般部署項目我們最好是集群,這樣可以高可用、高可靠。
一般的小公司,使用swarm就足夠了,如果非要使用K8S也是可以的……
為什么要使用集群?因為我們想要應用高可用,訪問的時候我們也不需要指定某個機器,如訪問redis數據庫,我們只需使用redis就好;當訪問量過大需要擴容時,你確定不用集群嗎?
這里我們主要體驗:創建服務、動態擴展服務、動態更新服務。
4.1 創建服務
4.1.1 查看服務docker service的基本命令
[root@iZ2vcf0atudng87wzoeel9Z ~]# 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.
4.1.2 查看創建服務的命令
[root@iZ2vcf0atudng87wzoeel9Z ~]# docker service create --help
Usage: docker service create [OPTIONS] IMAGE [COMMAND] [ARG...]
Create a new service
Options:
--cap-add list Add Linux capabilities
--cap-drop list Drop Linux capabilities
--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
--limit-pids int Limit maximum number of processes (default 0 = unlimited)
--log-driver string Logging driver for service
--log-opt list Logging driver options
--max-concurrent uint Number of job tasks to run concurrently (default equal to --replicas)
--mode string Service mode (replicated, global, replicated-job, or global-job) (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
--replicas-max-per-node uint Maximum number of tasks per node (default 0 = unlimited)
--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
--sysctl list Sysctl options
-t, --tty Allocate a pseudo-TTY
--ulimit ulimit Ulimit options (default [])
--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: <name|uid>[:<group|gid>])
--with-registry-auth Send registry authentication details to swarm agents
-w, --workdir string Working directory inside the container
4.1.3 創建一個服務
# elfin01
[root@iZ2vcf0atudng87wzoeel9Z ~]# docker service create -p 8888:80 --name my_nginx nginx
3zs3vzn8aqh6mjhoawbcysl96
overall progress: 1 out of 1 tasks
1/1: running [==================================================>]
verify: Service converged
注意:
- docker run 容器啟動!不具有擴縮容
- dockerservice 服務化啟動!具有擴縮容、滾動更新!
4.2 查看我們的服務
# elfin01
[root@iZ2vcf0atudng87wzoeel9Z ~]# docker service ps my_nginx
ID NAME IMAGE NODE DESIRED STATE CURRENT STATE ERROR PORTS
byfl43zh4ltb my_nginx.1 nginx:latest iZ2vcf0atudng87wzoeelaZ Running Running 3 minutes ago
# elfin03
[root@iZ2vcf0atudng87wzoeelbZ ~]# docker service ps my_nginx
ID NAME IMAGE NODE DESIRED STATE CURRENT STATE ERROR PORTS
byfl43zh4ltb my_nginx.1 nginx:latest iZ2vcf0atudng87wzoeelaZ Running Running 4 minutes ago
[root@iZ2vcf0atudng87wzoeelbZ ~]# docker service ls
ID NAME MODE REPLICAS IMAGE PORTS
3zs3vzn8aqh6 my_nginx replicated 1/1 nginx:latest *:8888->80/tcp
這里只啟動了一個nginx,只有一個副本,這好像部署我們想要的結果……
如果你想看具體的信息,可以使用docker service inspect my_nginx
,這里的命令和docker的基本命令相似,只是加了一個service。
4.3更新服務
查看update的基本命令
[root@iZ2vcf0atudng87wzoeelbZ ~]# docker service update --help
Usage: docker service update [OPTIONS] SERVICE
Update a service
Options:
--args command Service command args
--cap-add list Add Linux capabilities
--cap-drop list Drop Linux capabilities
--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
--limit-pids int Limit maximum number of processes (default 0 = unlimited)
--log-driver string Logging driver for service
--log-opt list Logging driver options
--max-concurrent uint Number of job tasks to run concurrently (default equal to --replicas)
--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
--replicas-max-per-node uint Maximum number of tasks per node (default 0 = unlimited)
--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
--sysctl-add list Add or update a Sysctl option
--sysctl-rm list Remove a Sysctl option
-t, --tty Allocate a pseudo-TTY
--ulimit-add ulimit Add or update a ulimit option (default [])
--ulimit-rm list Remove a ulimit option
--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: <name|uid>[:<group|gid>])
--with-registry-auth Send registry authentication details to swarm agents
-w, --workdir string Working directory inside the container
副本設置--replicas uint
設置服務有三個副本
[root@iZ2vcf0atudng87wzoeelbZ ~]# docker service update --replicas 3 my_nginx
my_nginx
overall progress: 3 out of 3 tasks
1/3: running [==================================================>]
2/3: running [==================================================>]
3/3: running [==================================================>]
verify: Service converged
此時elfin01~elfin03都有my_nginx項目了……
訪問:使用集群中的任何一個IP都可以訪問到!
4.4 更新2
使用docker service scale my_nginx=5
,這里動態擴縮容為副本數為5,實際上和4.1.5的update一樣。
4.5 刪除服務
$ docker service rm my_nginx
此時三個主節點都查不到服務!,在所有節點也找不到!
完!