DockerSwarm

docker swarm可以将多个主机组成一个容器集群平台。

首要条件是安装Docker服务

初始化集群

执行docker swarm init的节点会成为管理节点

docker swarm init
Swarm initialized: current node (ruuypevo8ft12zcz958dzic6l) is now a manager.

To add a worker to this swarm, run the following command:

    docker swarm join --token SWMTKN-1-27iqqemd47et7166bdb9i5390lnnomuabu03wuewkujo7wf6l9-6b216933j1x6milagi98onx4f 172.23.x.x:2377

To add a manager to this swarm, run 'docker swarm join-token manager' and follow the instructions.

根据输出提示信息,在其它要加入集群的节点执行docker swarm join命令,即可加入集群。 如果管理节点开启了防火墙,需要开放以下端口

  • 2377 端口是集群管理通信端口,只需要在管理节点开启

  • 7946 tcp,udp 是节点间通信使用端口

  • 4789 是 overlay network 使用的端口。

# firewalld
firewall-cmd --permanent --zone=public --add-port=2377/tcp
firewall--reload

# ufw
ufw allow 2377

docker swarm参数

  • 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

基本操作

yaml示例

version: '3.1'

services:

  db:
    image: mysql:8.0.25
    # NOTE: use of "mysql_native_password" is not recommended: https://dev.mysql.com/doc/refman/8.0/en/upgrading-from-previous-series.html#upgrade-caching-sha2-password
    # (this is just an example, not intended to be a production configuration)
    command: --default-authentication-plugin=mysql_native_password
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: passwd
    ports:
      - 3306:3306
    volumes:
      - /data/mysql:/var/lib/mysql
  web:
    image: nginx
    restart: always
    ports:
      - 80:80
# 查看节点
docker node ls

# 通过yaml文件部署服务
docker stack deploy -c dockerstack.yaml NAME

# 查看、管理部署的服务
docker stack [ls|ps|rm|services] NAME


# 查看服务
docker service ls

ID             NAME      MODE         REPLICAS   IMAGE          PORTS
txoup7bv0j3b   ops_db    replicated   1/1        mysql:8.0.25   *:3306->3306/tcp
kya8d7k7q391   ops_web   replicated   1/1        nginx:latest   *:80->80/tcp

# 调整容器副本数量,具体的名称以`docker service ls`命令结果中的NAME为准
docker service scale ops_web=2

ops_web scaled to 2
overall progress: 2 out of 2 tasks 
1/2: running   [==================================================>] 
2/2: running   [==================================================>] 
verify: Service converged 


# 查看ops_web服务副本数量变成了2
docker service ls

ID             NAME      MODE         REPLICAS   IMAGE          PORTS
txoup7bv0j3b   ops_db    replicated   1/1        mysql:8.0.25   *:3306->3306/tcp
kya8d7k7q391   ops_web   replicated   2/2        nginx:latest   *:80->80/tcp

最后更新于