Dynamically Pick The User Gui and UId Who's Running Docker at The Host from Entrypoint

Dynamically pick the user GUI and UID who's running Docker at the host from entrypoint

Your best bet is passing (optional) environment variables to your docker container that can be processed by your startup script.

docker-compose.yml:

version: '2.1'
services:
www:
image: somenginx
environment:
- ${UID}
- ${GID}

Then use the values of $UID/$GID in your entrypoint script for updating the user's uid/gid.

Sadly docker-compose does not provide the basic ability to reference the current user's UID/GID (relevant issue), so this approach requires each user to ensure the environment variables exist on the host. Example ~/.bashrc snippet that would take care of that:

export UID
export GID="$(id -g $(whoami))"

Not quite optimal but at the moment there is no better way unless you have some other host orchestration besides docker/docker-compose. A shell script that handles container start for example would make this trivial. Another approach is templating your docker-compose.yml via some external build tool like gradle that wraps docker-compose and takes care of inserting the current UID/GID before the containers are started.

usermod: UID '0' already exists why?

Because $UID in Bash expands to the current user id of the shell, and it's never empty, so [ -z "${UID}" ] is never true. So, you're setting uid=${UID};, probably uid=0 if the script runs as root.

Then usermod -u 0 www-data complains because it tries to change the UID of www-data to zero, but that's already in use, and it doesn't do that without the -o flag. (And you'd never want to do that anyway...)

If you want to test if $UID is zero, use [ "$UID" == 0 ]. Or [[ $UID == 0 ]] in Bash. Or [ "$UID" -eq 0 ] for a numeric comparison, not that it matters.

(I'm not exactly sure if changing the uid of www-data to 1000 is a good idea in any case, you already must have the user for usermod to be able to change its uid. But that wasn't the question.)

Bash:

UID
Expands to the user ID of the current user, initialized at shell startup. This variable is readonly.

usermod:

-u, --uid UID
The new numerical value of the user's ID.

This value must be unique, unless the -o option is used. The value must be non-negative.

How to set uid and gid in Docker Compose?

Try this

So, you need to put:

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

in your docker compose and provide UID and GID as docker-compose parameter

UID=${UID} GID=${GID} docker-compose up

(or define UID and GID as environment variables).



Related Topics



Leave a reply



Submit