docker,

Docker Compose and named volumes as non-root user

Jun 12, 2023 · 1 min read · Post a comment

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.

Prerequisites

  • Docker
  • Docker Compose

Solution(s)

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 depends_on and 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:

Conclusion

You can follow the official GitHub issue back from 2016. In case you face any issues, feel free to leave a comment below and if you find this tutorial useful, follow our official channel on Telegram.