Swarm
集群的管理和编号, docker初始化一个swarm集群, 其他节点可以加入 (管理者, 工作者)
Swarm工作模式: 管理节点(至少3个), 工作节点
官方文档: https://docs.docker.com/engine/swarm/how-swarm-mode-works/nodes/
Swarm命令帮助
[root@localhost ~]# 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.
Swarm初始化命令
[root@localhost ~]# 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)
初始化Swarm集群, 生成主节点
[root@localhost ~]# docker swarm init --advertise-addr 192.168.0.250
Swarm initialized: current node (xa4tcvtx0ss80pu7zsy975xf1) is now a manager.
To add a worker to this swarm, run the following command:
docker swarm join --token SWMTKN-1-2nz7pe5u74to8kkyqam343fa1ldkwbui5o5ang480nxcl55wvq-2o0qo4iazn44s0h4akqo00su5 192.168.0.250:2377
To add a manager to this swarm, run 'docker swarm join-token manager' and follow the instructions.
获取添加节点令牌
# 管理节点令牌
docker swarm join-token manager
# 工作节点令牌
docker swarm join-token worker
加入节点(manager, worker)
[root@localhost ~]# docker swarm join --token SWMTKN-1-2nz7pe5u74to8kkyqam343fa1ldkwbui5o5ang480nxcl55wvq-2o0qo4iazn44s0h4akqo00su5 192.168.0.250:2377
This node joined a swarm as a worker.
启动两个manager节点和两个worker节点, 查看当前节点状态
[root@localhost ~]# docker node ls
ID HOSTNAME STATUS AVAILABILITY MANAGER STATUS ENGINE VERSION
4detbmr2ziwikj91j9x6lsbhs localhost.localdomain Ready Active 19.03.13
7j34gp7d1xrijkwxy2nprmp89 localhost.localdomain Ready Active Reachable 19.03.13
tgvu8ep05zohd6x5h7ab9n8c6 localhost.localdomain Ready Active 19.03.13
xa4tcvtx0ss80pu7zsy975xf1 * localhost.localdomain Ready Active Leader 19.03.13
Raft协议
保证大多数节点存活才可用 (至少>2)
将主节点1停止测试
[root@localhost ~]# systemctl stop docker
Warning: Stopping docker.service, but it can still be activated by:
docker.socket
在给一个manager节点查看状态(剩余一个主节点, 集群不能工作)
[root@localhost ~]# docker node ls
Error response from daemon: rpc error: code = DeadlineExceeded desc = context deadline exceeded
[root@localhost ~]# 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.
重新启动主节点1, 重新查看节点状态
[root@localhost ~]# systemctl start docker
[root@localhost ~]# docker node ls
ID HOSTNAME STATUS AVAILABILITY MANAGER STATUS ENGINE VERSION
4detbmr2ziwikj91j9x6lsbhs localhost.localdomain Ready Active 19.03.13
7j34gp7d1xrijkwxy2nprmp89 localhost.localdomain Ready Active Leader 19.03.13
tgvu8ep05zohd6x5h7ab9n8c6 localhost.localdomain Ready Active 19.03.13
xa4tcvtx0ss80pu7zsy975xf1 * localhost.localdomain Ready Active Reachable 19.03.13
把其中一个worker
离开集群
[root@localhost ~]# docker swarm leave
Node left the swarm.
查看节点状态
[root@localhost ~]# docker node ls
ID HOSTNAME STATUS AVAILABILITY MANAGER STATUS ENGINE VERSION
4detbmr2ziwikj91j9x6lsbhs localhost.localdomain Ready Active 19.03.13
7j34gp7d1xrijkwxy2nprmp89 localhost.localdomain Ready Active Leader 19.03.13
tgvu8ep05zohd6x5h7ab9n8c6 localhost.localdomain Down Active 19.03.13
xa4tcvtx0ss80pu7zsy975xf1 * localhost.localdomain Ready Active Reachable 19.03.13
重新作为manager
加入集群
[root@localhost ~]# docker swarm join --token SWMTKN-1-2nz7pe5u74to8kkyqam343fa1ldkwbui5o5ang480nxcl55wvq-boj74lujjljzvyvtlprh0fqpa 192.168.0.250:2377
This node joined a swarm as a manager.
查看节点状态
[root@localhost ~]# docker node ls
ID HOSTNAME STATUS AVAILABILITY MANAGER STATUS ENGINE VERSION
4detbmr2ziwikj91j9x6lsbhs localhost.localdomain Ready Active 19.03.13
7j34gp7d1xrijkwxy2nprmp89 localhost.localdomain Ready Active Leader 19.03.13
msrkboug93zfzmf1s3koxtyx0 localhost.localdomain Ready Active Reachable 19.03.13
tgvu8ep05zohd6x5h7ab9n8c6 localhost.localdomain Down Active 19.03.13
xa4tcvtx0ss80pu7zsy975xf1 * localhost.localdomain Ready Active Reachable 19.03.13
再次停止一个主节点, 查看状态 (剩余两个主节点, 集群正常工作)
[root@localhost ~]# docker node ls
ID HOSTNAME STATUS AVAILABILITY MANAGER STATUS ENGINE VERSION
4detbmr2ziwikj91j9x6lsbhs localhost.localdomain Ready Active 19.03.13
7j34gp7d1xrijkwxy2nprmp89 * localhost.localdomain Ready Active Leader 19.03.13
msrkboug93zfzmf1s3koxtyx0 localhost.localdomain Ready Active Reachable 19.03.13
tgvu8ep05zohd6x5h7ab9n8c6 localhost.localdomain Down Active 19.03.13
xa4tcvtx0ss80pu7zsy975xf1 localhost.localdomain Ready Active Unreachable 19.03.13
弹性扩缩容
弹性, 扩缩容, 集群, 告别 docker run
!
单机: 启动一个项目: docker-compose up
集群: swarm, docker service
容器=>服务=>副本
redis服务=>10个副本 (同时开启10个redis容器)
docker服务
命令帮助
[root@localhost ~]# 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.
体验: 创建服务, 动态扩展服务, 动态更新服务
灰度发布: 金丝雀发布! (滚动发布)
创建服务命令帮助
[root@localhost ~]# 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-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
--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
--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
创建nginx服务
[root@localhost ~]# docker service create -p 8888:80 --name mynginx nginx
pqn9zyf0dvrrxwh8mwo66hwth
overall progress: 1 out of 1 tasks
1/1: running [==================================================>]
verify: Service converged
docker run
容器启动, 不具备扩缩容器
docker service
服务启动, 具备扩缩容器, 滚动更新
查看服务状态 (在任意一台manager
节点都可查看)
[root@localhost ~]# docker service ps mynginx
ID NAME IMAGE NODE DESIRED STATE CURRENT STATE ERROR PORTS
tjr17l8ryj6e mynginx.1 nginx:latest localhost.localdomain Running Running 2 minutes ago
[root@localhost ~]# docker service ls
ID NAME MODE REPLICAS IMAGE PORTS
pqn9zyf0dvrr mynginx replicated 1/1 nginx:latest *:8888->80/tcp
查看服务详细信息
[root@localhost ~]# docker service inspect mynginx
[
{
"ID": "pqn9zyf0dvrrxwh8mwo66hwth",
"Version": {
"Index": 49
},
"CreatedAt": "2020-12-09T09:10:21.105987803Z",
"UpdatedAt": "2020-12-09T09:10:21.110402331Z",
"Spec": {
"Name": "mynginx",
"Labels": {},
"TaskTemplate": {
"ContainerSpec": {
"Image": "nginx:latest@sha256:6b1daa9462046581ac15be20277a7c75476283f969cb3a61c8725ec38d3b01c3",
"Init": false,
"StopGracePeriod": 10000000000,
"DNSConfig": {},
"Isolation": "default"
},
"Resources": {
"Limits": {},
"Reservations": {}
},
"RestartPolicy": {
"Condition": "any",
"Delay": 5000000000,
"MaxAttempts": 0
},
"Placement": {
"Platforms": [
{
"Architecture": "amd64",
"OS": "linux"
},
{
"OS": "linux"
},
{
"OS": "linux"
},
{
"Architecture": "arm64",
"OS": "linux"
},
{
"Architecture": "386",
"OS": "linux"
},
{
"Architecture": "mips64le",
"OS": "linux"
},
{
"Architecture": "ppc64le",
"OS": "linux"
},
{
"Architecture": "s390x",
"OS": "linux"
}
]
},
"ForceUpdate": 0,
"Runtime": "container"
},
"Mode": {
"Replicated": {
"Replicas": 1
}
},
"UpdateConfig": {
"Parallelism": 1,
"FailureAction": "pause",
"Monitor": 5000000000,
"MaxFailureRatio": 0,
"Order": "stop-first"
},
"RollbackConfig": {
"Parallelism": 1,
"FailureAction": "pause",
"Monitor": 5000000000,
"MaxFailureRatio": 0,
"Order": "stop-first"
},
"EndpointSpec": {
"Mode": "vip",
"Ports": [
{
"Protocol": "tcp",
"TargetPort": 80,
"PublishedPort": 8888,
"PublishMode": "ingress"
}
]
}
},
"Endpoint": {
"Spec": {
"Mode": "vip",
"Ports": [
{
"Protocol": "tcp",
"TargetPort": 80,
"PublishedPort": 8888,
"PublishMode": "ingress"
}
]
},
"Ports": [
{
"Protocol": "tcp",
"TargetPort": 80,
"PublishedPort": 8888,
"PublishMode": "ingress"
}
],
"VirtualIPs": [
{
"NetworkID": "lh400xvkoitl0j2m82fo36zfy",
"Addr": "10.0.0.7/24"
}
]
}
}
]
动态扩缩容, 命令帮助
[root@localhost ~]# 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-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
--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
--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
扩容增加3个服务
[root@localhost ~]# docker service update --replicas 3 mynginx
mynginx
overall progress: 3 out of 3 tasks
1/3: running [==================================================>]
2/3: running [==================================================>]
3/3: running [==================================================>]
verify: Service converged
打开浏览器访问其中一台机器 (集群中任意节点都可以访问服务)
http://192.168.0.251:8888/
http://192.168.0.252:8888/
查看服务状态
[root@localhost ~]# docker service ps mynginx
ID NAME IMAGE NODE DESIRED STATE CURRENT STATE ERROR PORTS
tjr17l8ryj6e mynginx.1 nginx:latest localhost.localdomain Running Running 13 minutes ago
mhueaz21flcd mynginx.2 nginx:latest localhost.localdomain Running Running 3 minutes ago
4mm5nofddu9l mynginx.3 nginx:latest localhost.localdomain Running Running 3 minutes ago
同理可以开10个服务
[root@localhost ~]# docker service update --replicas 10 mynginx
mynginx
overall progress: 10 out of 10 tasks
1/10: running [==================================================>]
2/10: running [==================================================>]
3/10: running [==================================================>]
4/10: running [==================================================>]
5/10: running [==================================================>]
6/10: running [==================================================>]
7/10: running [==================================================>]
8/10: running [==================================================>]
9/10: running [==================================================>]
10/10: running [==================================================>]
verify: Service converged
查看状态
[root@localhost ~]# docker service ps mynginx
ID NAME IMAGE NODE DESIRED STATE CURRENT STATE ERROR PORTS
tjr17l8ryj6e mynginx.1 nginx:latest localhost.localdomain Running Running 14 minutes ago
mhueaz21flcd mynginx.2 nginx:latest localhost.localdomain Running Running 5 minutes ago
4mm5nofddu9l mynginx.3 nginx:latest localhost.localdomain Running Running 5 minutes ago
mejqy2fkwgjk mynginx.4 nginx:latest localhost.localdomain Running Running 32 seconds ago
z5eg7bh0ptcw mynginx.5 nginx:latest localhost.localdomain Running Running 25 seconds ago
gq8eqxysahty mynginx.6 nginx:latest localhost.localdomain Running Running 24 seconds ago
gwlev9d97r4k mynginx.7 nginx:latest localhost.localdomain Running Running 33 seconds ago
iyxfjoo95n4i mynginx.8 nginx:latest localhost.localdomain Running Running 33 seconds ago
zbc1bnaylyet mynginx.9 nginx:latest localhost.localdomain Running Running 33 seconds ago
6r52v2moaz1h mynginx.10 nginx:latest localhost.localdomain Running Running 23 seconds ago
在其他节点查看启动的容器 (每台机平均分布启动)
[root@localhost ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
7050665da76b nginx:latest "/docker-entrypoint.…" 54 seconds ago Up 53 seconds 80/tcp mynginx.9.zbc1bnaylyet5qu9xlzodl6op
b95f4c501d85 nginx:latest "/docker-entrypoint.…" 5 minutes ago Up 5 minutes 80/tcp mynginx.3.4mm5nofddu9lhtqkxnuwah0gg
[root@localhost ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
cc30d604f1dc nginx:latest "/docker-entrypoint.…" About a minute ago Up About a minute 80/tcp mynginx.10.6r52v2moaz1hd9tby9xa4xw5m
070e89444be0 nginx:latest "/docker-entrypoint.…" About a minute ago Up About a minute 80/tcp mynginx.6.gq8eqxysahtyw764pvgjd5t83
206a10c1165b nginx:latest "/docker-entrypoint.…" About a minute ago Up About a minute 80/tcp mynginx.5.z5eg7bh0ptcwxcg83y8dy3hv1
回滚容器(减少)
[root@localhost ~]# docker service update --replicas 1 mynginx
mynginx
overall progress: 1 out of 1 tasks
1/1: running [==================================================>]
verify: Service converged
查看状态
[root@localhost ~]# docker service ps mynginx
ID NAME IMAGE NODE DESIRED STATE CURRENT STATE ERROR PORTS
tjr17l8ryj6e mynginx.1 nginx:latest localhost.localdomain Running Running 18 minutes ago
scale命令扩缩容 (等于update)
[root@localhost ~]# docker service scale mynginx=5
mynginx scaled to 5
overall progress: 5 out of 5 tasks
1/5: running [==================================================>]
2/5: running [==================================================>]
3/5: running [==================================================>]
4/5: running [==================================================>]
5/5: running [==================================================>]
verify: Service converged
扩展
查看网络信息
[root@localhost ~]# docker network ls
NETWORK ID NAME DRIVER SCOPE
c4fd6b7dd5af bridge bridge local
c7ddd4a70168 docker_gwbridge bridge local
129beacda410 host host local
lh400xvkoitl ingress overlay swarm
21a55cd7b645 none null local
指定工作节点创建服务
--mode string Service mode (replicated or global) (default "replicated")
# 只在工作节点启动服务
docker service create --mode replicated -p 8888:80 --name mynginx nginx
Docker Stack
单机部署: docker-compose
集群部署: docker-Stack
# 单机
docker-compose up -d docker-compose.yml
# 集群
docker stack deploy docker-compose.yml
命令帮助
[root@localhost ~]# docker stack --help
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.
docker stack服务docker-compose.yml
version: "3"
services:
redis:
image: redis:alpine
ports:
- "6379"
networks:
- frontend
deploy:
replicas: 2
update_config:
parallelism: 2
delay: 10s
restart_policy:
condition: on-failure
db:
image: postgres:9.4
volumes:
- db-data:/var/lib/postgresql/data
networks:
- backend
deploy:
placement:
constraints: [node.role == manager]
vote:
image: dockersamples/examplevotingapp_vote:before
ports:
- 5000:80
networks:
- frontend
depends_on:
- redis
deploy:
replicas: 2
update_config:
parallelism: 2
restart_policy:
condition: on-failure
result:
image: dockersamples/examplevotingapp_result:before
ports:
- 5001:80
networks:
- backend
depends_on:
- db
deploy:
replicas: 1
update_config:
parallelism: 2
delay: 10s
restart_policy:
condition: on-failure
worker:
image: dockersamples/examplevotingapp_worker
networks:
- frontend
- backend
deploy:
mode: replicated
replicas: 1
labels: [APP=VOTING]
restart_policy:
condition: on-failure
delay: 10s
max_attempts: 3
window: 120s
placement:
constraints: [node.role == manager]
visualizer:
image: dockersamples/visualizer:stable
ports:
- "8080:8080"
stop_grace_period: 1m30s
volumes:
- "/var/run/docker.sock:/var/run/docker.sock"
deploy:
placement:
constraints: [node.role == manager]
portainer:
image: portainer/portainer
ports:
- "9000:9000"
volumes:
- "/var/run/docker.sock:/var/run/docker.sock"
deploy:
replicas: 1
placement:
constraints: [node.role == manager]
networks:
frontend:
backend:
volumes:
db-data:
Docker Secret
[root@localhost ~]# docker secret --help
Usage: docker secret COMMAND
Manage Docker secrets
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 Config
[root@localhost ~]# docker config --help
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.