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:

Dockerfile:

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

USER app

WORKDIR /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:

volumes:
    - 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?

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