一、不指定宿主机目录
首先运行一个Nginx容器
docker run -d --name myNginx -p 8080:80 -v /usr/share/Nginx/html Nginx
--name 指定容器名字
-v 表示把docker里面的目录/usr/share/Nginx/html映射出来
通过inspect命令查看宿主机对应的目录
docker inspect myNginx
省略部分输出
"Mounts": [
{
"Type": "volume",
"Name": "fd6a85bb7a90ad465de3c5720d65576bff273b15b112cd3e62bb0d9d3f4a0c7a",
"Source": "/var/lib/docker/volumes/fd6a85bb7a90ad465de3c5720d65576bff273b15b112cd3e62bb0d9d3f4a0c7a/_data",
"Destination": "/usr/share/Nginx/html",
"Driver": "local",
"Mode": "",
"RW": true,
"Propagation": ""
}
]
可以看到docker里面的目录/usr/share/Nginx/html对应到宿主机的目录为/var/lib/docker/volumes/354d406d5ec7f55bf445d70ac5f0534e1d185207a3f0b37e381af531a1d9ce37/_data
修改宿主机的文件
cd /var/lib/docker/volumes/354d406d5ec7f55bf445d70ac5f0534e1d185207a3f0b37e381af531a1d9ce37/_data
ls
50x.html index.html
vi index.html
<html>
<p1>hello, I am Nginx.</p1>
</html>
进入到docker目录
docker exec -it myNginx /bin/bash
cd /usr/share/Nginx/html/
cat index.html
<html>
<p1>hello, I am Nginx.</p1>
</html>
可以看到docker里面同步也进行了更改,打开网页http://10.40.16.61:8080/
二、指定宿主机目录
cd /tmp
mdkir html
vi html/index.html
<html>
<p1>hello, I change index file.</p1>
</html>
docker run -d --name myNginx1 -p 8081:80 -v $PWD/html:/usr/share/Nginx/html Nginx
$PWD表示当前路径
通过inspect命令查看宿主机对应的目录
docker inspect myNginx1
省略部分输出
"Mounts": [
{
"Type": "bind",
"Source": "/tmp/html",
"Destination": "/usr/share/Nginx/html",
"Mode": "",
"RW": true,
"Propagation": "rprivate"
}
]
三、卷组给多个容器共享
mkdir myvolumes
cd myvolumes
mkdir data
docker create -v $PWD/data:/var/mydata --name data_container centos
# docker create只创建容器但不运行
docker run -it --volumes-from data_container centos /bin/bash
# -it以交互方式运行
mount | grep data
/dev/sda2 on /var/mydata type xfs (rw,relatime,attr2,inode64,noquota)
可以看到容器data_container的/var/mydata目录同样也在新的容器的下
cd /var/mydata
touch nothing
exit