本文主要介绍多个容器之间如何共用同一个存储卷案例,以此实现类似nfs共享文件存储的功能
1、共享同一个存储卷
# 1、创建c1容器并指定存储卷
[root@docker101 ~]# docker volume ls
DRIVER VOLUME NAME
[root@docker101 ~]# docker container run -d -v /usr/share/nginx/html --name c1 -p 81:80 nginx:1.26.1-alpine
ef1853a0edb7b769f62a45f8ce2dd33a3bd312ed38e345d45084a14e34b3674d
[root@docker101 ~]# docker volume ls
DRIVER VOLUME NAME
local 387a178cbc85522a00521f80cf6d745764321e1faf25b91a9e555048f578654c
[root@docker101 ~]# docker container inspect -f "{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}" c1
172.17.0.2
# 2、创建c2容器和c1容器共用同一个存储卷
[root@docker101 ~]# docker volume ls
DRIVER VOLUME NAME
local 387a178cbc85522a00521f80cf6d745764321e1faf25b91a9e555048f578654c
[root@docker101 ~]# docker container run -d --volumes-from c1 --name c2 -p 82:80 nginx:1.26.1-alpine
773db0c3b64e99476dd6a859cda09d9d639fbf6ad55cf0a415208ab8286f6f8d
[root@docker101 ~]# docker volume ls
DRIVER VOLUME NAME
local 387a178cbc85522a00521f80cf6d745764321e1faf25b91a9e555048f578654c
[root@docker101 ~]# docker container inspect -f "{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}" c2
172.17.0.3
# 3、修改c2的网站页面
[root@docker101 ~]# docker exec -it c2 sh
/ # echo www.baidu.com > /usr/share/nginx/html/index.html
/ # exit
[root@docker101 ~]# curl 172.17.0.2
www.baidu.com
[root@docker101 ~]# curl 172.17.0.3
www.baidu.com
2、将宿主机的指定目录挂载到容器中
# 1、创建测试数据
[root@docker101 ~]# mkdir -pv /Dusk/code
[root@docker101 ~]#
[root@docker101 ~]# cat /Dusk/code/index.html
<h1 style='color: red;'>www.baidu.com</h1>
#2、挂载容器
[root@docker101 ~]# docker container run -d -p 83:80 -v /Dusk/code/:/usr/share/nginx/html nginx:1.26.1-alpine
02fc0554178f84493b4904e0458c79b1407734cf7c37bcbb70e1195e565ad1b4
[root@docker101 ~]# docker ps -l
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
02fc0554178f nginx:1.26.1-alpine "/docker-entrypoint.…" 4 seconds ago Up 4 seconds 0.0.0.0:83->80/tcp, :::83->80/tcp tender_mcclintock
[root@docker101 ~]# curl http://10.0.0.101:83/
<h1 style='color: red;'>www.baidu.com</h1>