Can I create a temporary variable in Dockerfile an

2019-08-07 14:57发布

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条回答
时光不老,我们不散
2楼-- · 2019-08-07 15:08

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.

查看更多
登录 后发表回答