How to set a user/group for running image, still using a Docker volume?

I would like to use Traefik as an rootless image, therefore supplying a user/group in compose. The challenge I have is that I need to supply a volume to persist LetsEncrypt certificates to not run into issuing limits. I expected a new volume to play nice with arbitrary user/group, but that seems not the case.

Example docker-compose.yml for docker compose and docker stack deploy:

version: '3.9'
    image: debian:stable-slim
    hostname: '{{.Node.Hostname}}'
    user: 1001:1002
      mode: global
      - debian-volume:/volume
    entrypoint: ["/bin/sh", "-c"]          
      - |
        echo Starting Debian
        cd /volume
        sleep 1000000
    name: debian-volume

As the volume is brand new and empty, I would expect that the container can simply create a file inside, but instead I see touch: cannot touch '': Permission denied.

So how can I use a container with uid/giu unknown on host to write to an attached Docker volume? Or is this not possible and the uid/gid always need to exist on host to write to a Docker Volume?

A uid is actually not something that “exists” on a host. It is just a number that is mapped to a username. So even if a username with the uid does not exist on the host, the uid stil can be used to set as an owner of a file. The same is true for group ids. This would be important to know when you bind mount a directory from the host to the container, but in the compose file example you indeed use a volume. If that volume was never used before and it was just created when you started the compose poroject, it will be owned by root. IF you want that to be writeable by a non-root user, you need to make it writeable. You could create an image in which you create “/volume” as a directory owned by the user you want to use in the container. Then when the volume is mounted, Docker will set the permissions. If /volume doesn’t exist, it will not happen. It doesn’t matter what user the process is owned by in the container.

I believe you already saw my blogpost and you have a similar requirement here, except I didn’t write about rootless containers.