docker,

Docker Compose and UID / GID

May 14, 2022 · 2 mins read · Post a comment
Docker Compose and UID / GID

Although you could set a user id and group id as part of a Docker image, let’s see how it can be done from Docker Compose too. I’ll use the following docker compose code part as an example:

version: "3.9"

services:
  web:
    image: node:current-alpine3.15
    user: $UID:$GID
    tty: true

Note: Adding the tty: true line was necessary cause the container will exit right after running docker-compose up -d.

You should get the following output:

WARNING: The UID variable is not set. Defaulting to a blank string.
WARNING: The GID variable is not set. Defaulting to a blank string.
Creating network "temp_default" with the default driver
Creating temp_web_1 ... done

As we could see UID and GID variables are not set. Here’s a few ways you could set them and get rid of the warning messages as well.

Prerequisites

  • Docker
  • Docker Compose

Solution(s)

Solution no.1

Use the current user’s UID and GID.

UID=$UID GID=$GID docker-compose up -d

Confirm the values. In my case:

docker exec -it temp_web_1 id -u
501
docker exec -it temp_web_1 id -g
20

Note(s):

  • Don’t forget to include UID, GID when taking the compose stack down.
    UID=$UID GID=$GID docker-compose down
    
  • You could also do the same with UID=$(id -u) GID=$(id -g) docker-compose up -d.
  • Overall, this is a lazy and security-wise not recommended solution especially if you are executing things as root / sudo user.

Solution no.2

A more convenient approach should be by applying the env vars in an .env file. For instance:

UID=1111
GID=2222

Solution no.3

In the docker compose file, either set custom values for UID and GID or override them by using docker-compose.override.yml file.

version: '3'  
 
services: 
  app: 
    user: 1111:2222

Solution no.4

Last but not least, remove or comment out the user: $UID:GID line from the compose file and use docker run instead. Basically you will execute commands against a single service (container) that will terminate once the command finish executing.

docker-compose run -u 1111:2222 web id -u
1111
docker-compose run -u 1111:2222 web id -g
2222

Conclusion

My two cents:

  1. Run Docker containers as non-root users by using the USER instruction as part of the Dockerfile.
  2. Run Docker in rootless mode.

If you can think of any other way, feel free to leave a comment below.
On another note, follow our official channel on Telegram.