多个机器之间的容器共享数据

multi-host-volume

官方参考链接 https://docs.docker.com/storage/volumes/#share-data-among-machines

Docker的volume支持多种driver。默认创建的volume driver都是local

  1. $ docker volume inspect vscode
  2. [
  3. {
  4. "CreatedAt": "2021-06-23T21:33:57Z",
  5. "Driver": "local",
  6. "Labels": null,
  7. "Mountpoint": "/var/lib/docker/volumes/vscode/_data",
  8. "Name": "vscode",
  9. "Options": null,
  10. "Scope": "local"
  11. }
  12. ]

这一节我们看看一个叫sshfs的driver,如何让docker使用不在同一台机器上的文件系统做volume

环境准备

准备三台Linux机器,之间可以通过SSH相互通信。

hostname ip ssh username ssh password
docker-host1 192.168.200.10 vagrant vagrant
docker-host2 192.168.200.11 vagrant vagrant
docker-host3 192.168.200.12 vagrant vagrant

安装plugin

在其中两台机器上安装一个plugin vieux/sshfs

  1. [vagrant@docker-host1 ~]$ docker plugin install --grant-all-permissions vieux/sshfs
  2. latest: Pulling from vieux/sshfs
  3. Digest: sha256:1d3c3e42c12138da5ef7873b97f7f32cf99fb6edde75fa4f0bcf9ed277855811
  4. 52d435ada6a4: Complete
  5. Installed plugin vieux/sshfs
  1. [vagrant@docker-host2 ~]$ docker plugin install --grant-all-permissions vieux/sshfs
  2. latest: Pulling from vieux/sshfs
  3. Digest: sha256:1d3c3e42c12138da5ef7873b97f7f32cf99fb6edde75fa4f0bcf9ed277855811
  4. 52d435ada6a4: Complete
  5. Installed plugin vieux/sshfs

创建volume

  1. [vagrant@docker-host1 ~]$ docker volume create --driver vieux/sshfs \
  2. -o sshcmd=vagrant@192.168.200.12:/home/vagrant \
  3. -o password=vagrant \
  4. sshvolume

查看

  1. [vagrant@docker-host1 ~]$ docker volume ls
  2. DRIVER VOLUME NAME
  3. vieux/sshfs:latest sshvolume
  4. [vagrant@docker-host1 ~]$ docker volume inspect sshvolume
  5. [
  6. {
  7. "CreatedAt": "0001-01-01T00:00:00Z",
  8. "Driver": "vieux/sshfs:latest",
  9. "Labels": {},
  10. "Mountpoint": "/mnt/volumes/f59e848643f73d73a21b881486d55b33",
  11. "Name": "sshvolume",
  12. "Options": {
  13. "password": "vagrant",
  14. "sshcmd": "vagrant@192.168.200.12:/home/vagrant"
  15. },
  16. "Scope": "local"
  17. }
  18. ]

创建容器挂载Volume

创建容器,挂载sshvolume到/app目录,然后进入容器的shell,在/app目录创建一个test.txt文件

  1. [vagrant@docker-host1 ~]$ docker run -it -v sshvolume:/app busybox sh
  2. Unable to find image 'busybox:latest' locally
  3. latest: Pulling from library/busybox
  4. b71f96345d44: Pull complete
  5. Digest: sha256:930490f97e5b921535c153e0e7110d251134cc4b72bbb8133c6a5065cc68580d
  6. Status: Downloaded newer image for busybox:latest
  7. / #
  8. / # ls
  9. app bin dev etc home proc root sys tmp usr var
  10. / # cd /app
  11. /app # ls
  12. /app # echo "this is ssh volume"> test.txt
  13. /app # ls
  14. test.txt
  15. /app # more test.txt
  16. this is ssh volume
  17. /app #
  18. /app #

这个文件我们可以在docker-host3上看到

  1. [vagrant@docker-host3 ~]$ pwd
  2. /home/vagrant
  3. [vagrant@docker-host3 ~]$ ls
  4. test.txt
  5. [vagrant@docker-host3 ~]$ more test.txt
  6. this is ssh volume