Docker Swarm是轻量级的Docker集群解决方案。实现swarm集群应用数据持久化的一种方法是使用NFS共享存储。
sudo yum -y install nfs-utils
sudo systemctl start nfs
sudo systemctl enable nfs
sudo firewall-cmd --permanent --add-service=rpc-bind
sudo firewall-cmd --permanent --add-service=mountd
sudo firewall-cmd --permanent --add-port=2049/tcp
sudo firewall-cmd --permanent --add-port=2049/udp
sudo firewall-cmd --reload
sudo mkdir /nfs
vi /etc/exports
输入以下内容:
/nfs 192.168.52.0/24(rw,no_root_squash)
sudo exportfs -rav
showmount -e 192.168.52.141
sudo mkdir /mynfs
sudo mount -t nfs 192.168.52.141:/nfs /mynfs
在/mynfs目录中创建文件,然后在NFS服务端的共享目录中查看文件是否存在,存在则代表共享成功。
umount /mynfs
既然是集群,我们就不会希望跑到每个节点上面去配置NFS挂载和映射。做集群共享卷的关键,就是在compose文件中创建volume。语法如下:
volumes:
my-vol:
driver_opts:
type: "nfs"
o: "addr=192.168.52.141,rw"
device: ":/volume1/swarm"
下面来一个复杂一点的 stack 配置,有 Prometheus 与 Grafana 两个容器,其中 Grafana 挂载 NFS 卷作为持久化存储,两个容器通过 overlay 网络互访。
version: '3.7'
services:
grafana:
image: grafana/grafana:latest
hostname: grafana
deploy:
restart_policy:
delay: 10s
max_attempts: 10
window: 60s
networks:
- monitor_distributed
ports:
- 3000:3000
volumes:
- grafana-data:/var/lib/grafana
prometheus:
image: prom/prometheus:latest
hostname: prometheus
deploy:
restart_policy:
delay: 10s
max_attempts: 10
window: 60s
networks:
- monitor_distributed
networks:
monitor_distributed:
driver: overlay
volumes:
grafana-data:
driver_opts:
type: "nfs"
o: "addr=192.168.52.141,rw"
device: ":/volume1/grafana"
docker stack deploy -c docker-compose.yaml monitor_stack
docker service scale monitor_stack_grafana=2
在worker节点执行命令查看数据卷
docker volume ls
docker volume inspect monitor_stack_grafana-data
结果如下:
[
{
"CreatedAt": "2020-08-27T20:21:45Z",
"Driver": "local",
"Labels": {
"com.docker.stack.namespace": "monitor_stack"
},
"Mountpoint": "/var/lib/docker/volumes/monitor_stack_grafana-data/_data",
"Name": "monitor_stack_grafana-data",
"Options": {
"device": ":/volume1/grafana",
"o": "addr=192.168.52.141,rw",
"type": "nfs"
},
"Scope": "local"
}
]
可以看到,实际上 NFS 目录还是被挂载到节点宿主机上的。
为了确认挂载成功,还可以在 worker 节点 grafana 容器的共享目录创建文件,然后在 manager 节点 grafana 容器的共享目录中查看文件是否存在。