Docker Community Forums

Share and learn in the Docker community.

How to preserve the directory ownership of a container directory while it is mounted to the host volume?

I have a Dockerfile that looks like this:


RUN mkdir /app/public/documents \
    && chown -R app:app /app \
    && chmod -R 777 /app

USER app


Here’s a part of my stack file where I’m binding the directory I’ve created in the Dockerfile to a directory on the host file system:

Stack file:

    - docs:/app/public/documents

When I build and run the image, the permission and ownership on the app directory appear as configured in the Dockerfile, i.e app:app . However when I deploy the stack file using the docker stack deploy command the ownership of the documents directory in the container differs from what I intended it to be, its supposed to be app:app but it takes 1001:1001 . I figured out that the directory in the container was inheriting the ownership of the directory that’s on the host’s filesystem and 1001 actually turns out the be the user ID of the owner of the directory on the host filesystem. Is there anyway I can prevent the container directory to inherit the host directory’s ownership when the stack is deployed? Perhaps force it somehow to use the perms and ownership that’s defined in the Dockerfile?

If you chown the volume (on the host side) before bind-mounting it, it will work.
In that case, you could do:

mkdir /tmp/www
chown 101:101 /tmp/www
docker run -v /tmp/www:/var/www ubuntu stat -c “%U %G” /var/www
(Assuming that 101:101 is the UID:GID of the www-data user in your container.)

Another possibility is to do the bind-mount, then chown inside the container.

1 Like

Thanks for taking the time to answer my question. Is there any way I can achieve this using the stack file?

Simply put: docker-compose does not address folder ownership on the host side. Wouldn’t it be a major security concern, if people mount host folders they have no access to, into a container and can do inside that folder whatever they please?

bind-mount literally uses mount --bind for the os to mount a host path into a container path. Like with every mount, the mount source declares the permission mask and ownership. You need to change ownership of the host folder, to the same uid/gid of the user that executes the main process inside the container.

1 Like