Can I create a temporary variable in Dockerfile and reuse it later?


April 2019


35 time


In my Dockerfile, I want to temporarily switch to root and then switch back to the original user.

originalUser=`RUN whoami`

USER root
RUN apk update
RUN apk add curl

# switch back to the user before root
USER $originalUser

Is it possible to do something like this in Dockerfile?

1 answers


On the one hand, no, there's nothing like this. The only similar things are ARG (which get passed at the command line) and ENV (which are fixed strings), neither of which can be set dynamically based on command outputs.

On the other hand, within the context of a Docker image, you, as the Dockerfile author, have complete and absolute control over what goes into the image. You never have to ask questions like "what if the user has a different username" or "what if they want to install into a different path": you get to pick fixed values for these things. I would suggest:

  • If you're installing a single binary or something with a "normal" installation procedure (it has an Autoconf-style ./configure --prefix=... option), install it into the system directories
  • If you're installing something in a scripting language that doesn't go into the "normal" directories, /app is a common place for it
  • Install software exclusively as root (even your application); switch to a non-root USER just once at the end of your Dockerfile
  • Don't try to mirror any particular system's directory layout, user names, or numeric user IDs; if you try to run the image somewhere else they won't match

If you're trying to extend some other image, you should be fine figuring out what username it uses and putting a fixed string in a USER directory at the end of your derived image's Dockerfile.