Sharing named volumes or bind mounts between Docker Compose services as unprivileged / non-root user has always been tricky. By default, they all run as root. So, here are few solutions you could try to run your Docker Compose stack securely ..in a way.
- Docker Compose
The easier “hacky” approach would include alternating the Dockerfile itself. You would have something like this:
RUN useradd --system --uid 1000 --group nonroot --shell /sbin/nologin nonroot RUN mkdir /some_volume && chown nonroot:nonroot /some_volume USER nonroot
Which can get the work done if the files under the desired shared volume are baked into the image, which more often that’s not the case.
A better more suitable solution would be to include kind of a sidecar container that would update the volume ownership with the help of
service_completed_successfully. Take this example:
version: "3.9" services: change-ownership: image: alpine user: root group_add: - 'nonroot' volumes: - some-volume:/tmp/some_volume command: chown -R nonroot:nonroot /tmp/some_volume my-service: image: ubuntu user: nonroot group_add: - 'nonroot' volumes: - some-volume:/tmp/some_volume depends_on: change-ownership: condition: service_completed_successfully volumes: some-volume: