Jose Cabrera Zuniga
Jose Cabrera Zuniga

Reputation: 2627

Detecting username in Dockerfile

I need to run a cmd that will create my home folder within a docker container. So, if my username in my linux box is josecz then I could use it from within a Dockerfile to run a cmd like:

RUN mkdir /home/${GetMyUsername}

and get the folder /home/josecz after the Dockerfile is processed.

Upvotes: 2

Views: 5468

Answers (1)

atline
atline

Reputation: 31664

The only way just as commented by folks: use ARG, next gives you a workable minimal example:

Dockerfile:

FROM alpine:3.14.0

ARG GetMyUsername

RUN echo ${GetMyUsername}
RUN mkdir -p /home/${GetMyUsername}

Execution:

cake@cake:~/3$ docker build --build-arg GetMyUsername=`whoami` -t abc:1 . --no-cache
Sending build context to Docker daemon  2.048kB
Step 1/4 : FROM alpine:3.14.0
 ---> d4ff818577bc
Step 2/4 : ARG GetMyUsername
 ---> Running in 4d87a0970dbd
Removing intermediate container 4d87a0970dbd
 ---> 8b67912b3788
Step 3/4 : RUN echo ${GetMyUsername}
 ---> Running in 2d68a7e93715
cake
Removing intermediate container 2d68a7e93715
 ---> 100428a1c526
Step 4/4 : RUN mkdir -p /home/${GetMyUsername}
 ---> Running in 938d10336daa
Removing intermediate container 938d10336daa
 ---> 939729b76f09
Successfully built 939729b76f09
Successfully tagged abc:1

Explaination:

When docker build, you could use whoami to get the username who run the docker build, then pass to args GetMyUsername. Then, in Dockerfile, you could use ${GetMyUsername} to get the value.

Upvotes: 1

Related Questions