大网数据广告活动
服务器运维问答

Change permissions for named volumes in Docker

· 52CE 我爱测

I have Docker container with named volume running on non-root user started with the following command: docker run -v backup:/backup someimage In the image, there's a backup script which is trying to save files in /backup director…

问题原文

原帖链接 · QkiZ · CC BY-SA 4.0

I have Docker container with named volume running on non-root user started with the following command:

docker run -v backup:/backup someimage

In the image, there's a backup script which is trying to save files in /backup directory but it fails. Mounted backup volume in /backup dir belongs to root user.

How to change permissions for /backup directory?

-----EDIT1:

mcve below:

Run docker container with Gerrit:

docker run -v backupgerrit:/backup --name gerrit gerritcodereview/gerrit

Now on other terminal window try to save something in /backup dir:

docker exec gerrit touch /backup/testfile

You will get:

touch: cannot touch '/backup/testfile': Permission denied

已采纳解答

原帖链接 · BMitch · CC BY-SA 4.0

Named volumes are initialized when first created to the contents of the image at the mount location. That initialization includes the owner and permissions. If /backup does not exist in your image, then an empty directory will be created and owned by root. You can:

Option 1: Create the directory in your Dockerfile with the appropriate ownership and permissions:

FROM your-image
USER root
RUN mkdir -p /backup \
 && chown -R your-user /backup
USER your-user

Note, this only works when the backup named volume does not already exist or is empty. And it needs to be a named volume, not a host volume.

Option 2: Initialize the named volume, including some content inside the volume (an empty file would work) using another temporary container:

docker run --rm -v backupgerrit:/backup busybox \
  /bin/sh -c 'touch /backup/.initialized && chown -R 1000:1000 /backup'

Option 3: Adjust the permissions after the volume is mounted, requiring root inside your container:

docker exec -u 0:0 your-container chown -R your-user /backup

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2019-09-17)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。