只读挂载与权限
数据挂载时可配置访问权限,下面介绍只读挂载与权限处理。
只读挂载
Bash
# 挂载为只读
docker run -d -v /host/data:/container/data:ro nginx
# 使用命名卷只读挂载
docker run -d -v my-data:/container/data:ro nginx
# 多个挂载混合
docker run -d \
-v /host/config:/app/config:ro \
-v /host/data:/app/data:rw \
nginx
:ro表示只读(read-only),:rw表示读写(默认值)。
权限模式
Docker 默认以 root 用户在容器内操作文件,可能遇到权限问题:
Bash
# 宿主机文件权限
ls -la /host/data
# drwxr-xr-x 2 root root 4096 Jan 1 10:00 .
# 容器内以非 root 用户运行
docker run -d -v /host/data:/app/data -u www-data nginx
处理权限问题
Bash
# 方法1:修改宿主机文件权限
sudo chmod 777 /host/data
# 方法2:使用相同 UID 运行
docker run -d -v /host/data:/app/data -u $(id -u):$(id -g) nginx
# 方法3:在 Dockerfile 中设置用户
# USER www-data
挂载选项
Bash
# SELinux 标签
docker run -d -v /host/data:/container/data:Z nginx # 私有标签
docker run -d -v /host/data:/container/data:z nginx # 共享标签
# 挂载选项(较新 Docker 版本)
docker run -d --mount type=bind,source=/host/data,target=/app/data,readonly nginx
| 选项 | 说明 |
|---|---|
:ro | 只读挂载 |
:rw | 读写(默认) |
:Z | 设置私有 SELinux 标签 |
:z | 设置共享 SELinux 标签 |
--mount vs -v
--mount 语法更明确,推荐复杂场景使用:
Bash
# -v 语法
docker run -d -v /host/data:/app/data:ro nginx
# --mount 语法(等价)
docker run -d \
--mount type=bind,source=/host/data,target=/app/data,readonly \
nginx
# 命名卷
docker run -d \
--mount type=volume,source=my-data,target=/app/data,readonly \
nginx
--mount语法更冗长但更清晰,适合脚本和 Compose 文件。
要点总结
:ro只读挂载容器内无法修改,:rw读写(默认)- 权限问题可通过修改宿主机权限或指定 UID 解决
- SELinux 环境使用
:Z(私有)或:z(共享)选项 --mount语法比-v更清晰,推荐复杂场景使用- 配置文件建议只读挂载,防止容器内误修改
📝 发现内容有误?点击此处直接编辑