bashshelldockerdocker-compose

How to set uid and gid in Docker Compose?


I can execute a docker run command as such ...

docker run --rm  --user $(id -u):$(id -g) -e MYDATA=/some/path/to/data -e USER=$USER -p 8883-8887:8883-8887 ...

However, in Docker Compose, when I write out the following ...

version: '3.7'
services:
  container_name: some-server
  image: some:img
  user: $(id -u):$(id -g) 
  ... 

... it does not work.

I understand I am asking docker-compose up to perform sub shell command substitution, and it cannot.

Is there any way to do this?


Solution

  • Try this

    So, you need to put:

    user: "${UID_GID}"
    

    in your docker compose and provide UID_GID as docker-compose parameter

    UID_GID="$(id -u):$(id -g)" docker-compose up
    

    OR

    put

    user: "${UID}:${GID}"
    

    in your docker compose and export UID and GID as environment variables

    export UID
    export GID="$(id -g)"
    docker-compose up
    # OR skip exporting GID and do 
    # GID="$(id -g)" docker-compose up
    

    UID is a shell variable and exporting it again by specifying a value as export UID=${UID} fails the command with "-bash: UID: readonly variable" and unfortunately it also creates an environment variable UID and sets UID shell variable value to it. To prevent it from failing, don't specify a value and it will work.