$ docker-machine ls
NAME ACTIVE DRIVER STATE URL SWARM DOCKER ERRORS
manager1 - virtualbox Running tcp://192.168.99.100:2376 v1.12.0-rc2
worker1 - virtualbox Running tcp://192.168.99.101:2376 v1.12.0-rc2
worker2 - virtualbox Running tcp://192.168.99.102:2376 v1.12.0-rc2
创建Swarm集群
首先,切换到 manager1 主机,使用 docker swarm init 命令创建一个集群:
1234
$ eval $(docker-machine env manager1)
$ docker swarm init --listen-addr 192.168.99.100:2377
Swarm initialized: current node (alq8w7fi34f41j3z4ise1vkd7) is now a manager.
使用 docker info 确认一下当前节点信息,可以看到Swarm属性部分:
12345678910
$ docker info
... ...
Swarm: active
NodeID: alq8w7fi34f41j3z4ise1vkd7
IsManager: Yes
Managers: 1
Nodes: 1
CACertHash: sha256:7a9d0eb1621afe2be07c5fd405b8f038c76be3a8dc7b2c73944a2d1ab9dffd76
... ...
在2台worker节点上,通过 docker swarm join 命令加入到刚才创建的集群中:
123456789
$ eval $(docker-machine env worker1)
$ docker swarm join 192.168.99.100:2377
This node joined a Swarm as a worker.
$ docker info
... ...
Swarm: active
NodeID: 4l2a9ebgmcpwqlo0roye0n6m5
IsManager: No
... ...
回到 manager1 节点,确认一下集群中节点的个数和状态。在 MANAGER STATUS 属性中,可以看到谁是Leader:
123456
$ eval $(docker-machine env manager1)
$ docker node ls
ID NAME MEMBERSHIP STATUS AVAILABILITY MANAGER STATUS
4l2a9ebgmcpwqlo0roye0n6m5 worker1 Accepted Ready Active
alq8w7fi34f41j3z4ise1vkd7 * manager1 Accepted Ready Active Leader
e0khh79c6owm0e14mli602q0a worker2 Accepted Ready Active
$ docker service tasks nginx
ID NAME SERVICE IMAGE LAST STATE DESIRED STATE NODE
394by1b72i44a44jms2xwk6ud nginx.1 nginx nginx Preparing 9 seconds Running manager1
注意上面的 STATE 字段中刚开始的服务状态为 Preparing,需要等一会才能变为 Running 状态,其中最费时间的应该是下载镜像的过程。
$ docker service tasks nginx
ID NAME SERVICE IMAGE LAST STATE DESIRED STATE NODE
394by1b72i44a44jms2xwk6ud nginx.1 nginx nginx Running About a minute Running manager1
# 通过curl查看服务是否正常运行
$ curl http://192.168.99.100/
...
对服务进行扩展(scale)
当然,如果只是通过service启动容器,swarm也算不上什么新鲜东西了。Service还提供了复制(类似k8s里的副本)功能。可以通过 docker service scale 命令来设置服务中容器的副本数:
$ docker service tasks nginx
ID NAME SERVICE IMAGE LAST STATE DESIRED STATE NODE
394by1b72i44a44jms2xwk6ud nginx.1 nginx nginx Running 22 minutes Running manager1
co0re9u7infoo9qiegm6yiqcn nginx.2 nginx nginx Running 19 minutes Running worker1
19dvayah8fjz3vykrl2oi12uu nginx.3 nginx nginx Running 19 minutes Running worker1
991v97eg9q1hnnzxda6c9mmv7 nginx.4 nginx nginx Running 20 seconds Running manager1
e9yztfmy5luaxnadz80e5j8nl nginx.5 nginx nginx Running 20 seconds Running manager1
除了上面用到的一些命令, docker service 还有以下一些子命令:
12345678910111213141516171819
$ docker service --help
Usage: docker service COMMAND
Manage Docker services
Options:
--help Print usage
Commands:
create Create a new service
inspect Inspect a service
tasks List the tasks of a service
ls List services
rm Remove a service
scale Scale one or multiple services
update Update a service
Run 'docker service COMMAND --help' for more information on a command.