Docker:目录挂载、数据卷
- 1. 挂载
- 2. 卷映射
1. 挂载
-v /app/nghtml:/usr/share/nginx/html
/app/nghtml 是外部主机的地址
/usr/share/nginx/html 是内部容器的地址
这里启动一个nginx,然后在后台运行时其命令为
(base) ➜ ~ docker run -d -p 80:80 -v /app/nghtml:/usr/share/nginx/html --name app01 nginx
Unable to find image 'nginx:latest' locally
latest: Pulling from library/nginx
bb3f2b52e6af: Pull complete
e4bc5c1a6721: Pull complete
e93f7200eab8: Pull complete
1bd52ec2c0cb: Pull complete
411a98463f95: Pull complete
ad5932596f78: Pull complete
df25b2e5edb3: Pull complete
Digest: sha256:fb197595ebe76b9c0c14ab68159fd3c08bd067ec62300583543f0ebda353b5be
Status: Downloaded newer image for nginx:latest
515b8e2e537707543e227f2115b5cc5496f8bff16fd0eb245000c1e1fe6bcfcb
docker: Error response from daemon: Mounts denied:
The path /app/nghtml is not shared from the host and is not known to Docker.
You can configure shared paths from Docker -> Preferences... -> Resources -> File Sharing.
See https://docs.docker.com/desktop/settings/mac/#file-sharing for more info.
这个地址看到是不允许的 /app/nghtml
我换个地址
(base) ➜ ~ docker run -d -p 80:80 -v /Users/fanzhen/nghtml:/usr/share/nginx/html --name app01 nginx:latest
9c77c3e55bfd0308c6b168ae5c1b2ca74b46b03fb9c4e57bed10f06618676c49
删除刚才启动失败的容器
(base) ➜ ~ docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
515b8e2e5377 nginx "/docker-entrypoint.…" 2 minutes ago Created app01
04eae9666335 nginx:1.26.0 "/docker-entrypoint.…" 23 hours ago Exited (0) 22 hours ago nginx001
ab0201efd1e8 nginx:1.26.0 "/docker-entrypoint.…" 23 hours ago Exited (0) 23 hours ago naughty_mayer
ca16b2e7880b nginx:1.26.0 "/docker-entrypoint.…" 23 hours ago Exited (0) 23 hours ago nostalgic_montalcini
c7b8cbccf64c nginx:1.26.0 "/docker-entrypoint.…" 23 hours ago Exited (0) 23 hours ago zealous_euler
5425400480ac docker/welcome-to-docker:latest "/docker-entrypoint.…" 26 hours ago Up 26 hours 0.0.0.0:8088->80/tcp welcome-to-docker
(base) ➜ ~ docker rm -f app01
app01
看到返回了403,是因为直接走的外面的(主机)的,主机的nghtml文件夹里面什么也没有,这就需要我们在这个文件夹新建一个index.html文件
(base) ➜ nghtml ls
(base) ➜ nghtml echo 22222>index.html
(base) ➜ nghtml ls
index.html
再次刷新就有结果了
挂载容器与主机的数据是同步的,无论修改那一边数据都会同步到另一方
(base) ➜ nghtml docker exec -it 9c7 bash
root@9c77c3e55bfd:/# ls
bin boot dev docker-entrypoint.d docker-entrypoint.sh etc home lib media mnt opt proc root run sbin srv sys tmp usr var
root@9c77c3e55bfd:/# cd /usr/share/nginx/html
root@9c77c3e55bfd:/usr/share/nginx/html# ls
index.html
2. 卷映射
卷映射语法 -v ngconf:/etc/nginx
ngconf是卷名
/etc/nginx 是容器卷映射的目录
启动一个nginx,/Users/fanzhen/ngconf映射/etc/nginx
(base) ➜ docker run -d -p 99:80 -v ngconf:/etc/nginx --name app03 nginx:latest
aaaa918b51710fc1a62a864da175dd2dbd7f3a1e1fbf49e68e547c3cb9e35c5f