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
Best Answer
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:
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:
Option 3: Adjust the permissions after the volume is mounted, requiring root inside your container: