Change permissions for named volumes in Docker

Solution 1:

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