user3074620
user3074620

Reputation: 3977

Can I use an environment variable in a Dockerfile USER statement?

So my Dockerfile is written like so:

# set env vars for linux user
ENV LINUX_USER="kbuser"
...
... # other stuff
...
USER kbuser

But I would like to use

USER $LINUX_USER

So that I only have to write the username in one place in the file. But this doesn't work.

How can I get around this?

Thank you.

Upvotes: 4

Views: 6518

Answers (1)

Kevin Kopf
Kevin Kopf

Reputation: 14230

Use the ARG directive. As per docs:

ARG <name>[=<default value>]

The ARG instruction defines a variable that users can pass at build-time to the builder with the docker build command using the --build-arg <varname>=<value> flag. If a user specifies a build argument that was not defined in the Dockerfile, the build outputs a warning.

So you can actually use ARG like so:

ARG user=kbuser
USER $user

And you can actually set the argument when building the docker image:

docker build --build-arg user=banana .

There is much more to it in the docs, so you better read thoroughly.

Upvotes: 5

Related Questions