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(s): Adding the
tty: true line was necessary because 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.
- Docker Compose
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
- Don’t forget to include UID, GID when taking the Docker 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.
A more convenient approach should be by applying the env vars in an .env file. For instance:
Now, 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
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
My two cents:
- Run Docker containers as non-root users by using the USER instruction as part of the Dockerfile.
- 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.