Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass host user to Dockerfile when using docker-compose

I'm trying to pass a host variable to a Dockerfile when running docker-compose build

I would like to run

RUN usermod -u $USERID www-data

in an apache-php7 Dockerfile. $USERID being the ID of the current host user.

I would have thought that the following might work:

commandline

EXPORT USERID=$(id -u); docker-compose build

docker-compose.yml

...
environment:
    - USERID=$USERID

Dockerfile

ENV USERID 
RUN usermod -u $USERID www-data

But no luck yet.

like image 225
mgherkins Avatar asked Jan 07 '23 07:01

mgherkins


1 Answers

For Docker in general it is generally not possible to use host environment variables during the build phase; this is because it is desirable that if you run docker build and I run docker build using the same Dockerfile (or Docker Hub runs `docker build with the same Dockerfile), we end up with the same image, regardless of our local environment.

While passing in variables at runtime is easy with the docker command line (using -e <var>=<value>), it's a little trickier with docker-compose, because that tool is designed to create self-contained environments.

A simple solution would be to drop the host uid into an environment file before starting the container. That is, assuming you have:

version: "2"

services:
  shell:
    image: alpine
    env_file: docker-compose.env
    command: >
      env

You can then:

echo HOST_UID=$UID > docker-compose.env; docker-compose up

And the HOST_UID environment variable will be available to your container:

Recreating vartest_shell_1
Attaching to vartest_shell_1
shell_1  | HOSTNAME=17423d169a25
shell_1  | HOST_UID=1000
shell_1  | HOME=/root
vartest_shell_1 exited with code 0

You would then to have something like an ENTRYPOINT script that would set up the container environment (creating users, modifying file ownership) to operate correctly with the given UID.

like image 147
larsks Avatar answered Jan 08 '23 20:01

larsks