我可以在Dockerfile中创建一个临时变量并在以后重用吗? [英] Can I create a temporary variable in Dockerfile and reuse it later?

查看:307
本文介绍了我可以在Dockerfile中创建一个临时变量并在以后重用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Dockerfile中,我想暂时切换到root用户,然后再切换回原始用户。

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

是否可以在Dockerfile中执行类似的操作?

Is it possible to do something like this in Dockerfile?

推荐答案

一方面,不,没有类似的东西。唯一类似的内容是 ARG (在命令行中传递)和 ENV (它们是固定字符串),

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.

另一方面,在Docker映像的上下文中,作为Dockerfile的作者,您具有完整且完整的信息。完全控制进入图像的内容。您无需再问诸如如果用户使用不同的用户名该怎么办或如果他们要安装在其他路径中该怎么办之类的问题:您可以为这些事情选择固定值。我建议:

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:


  • 如果您要安装单个二进制文件或带有常规安装过程的东西(它具有Autoconf样式 ./ configure --prefix = ... 选项),将其安装到系统目录中

  • 如果要在一种不会进入普通目录的脚本语言, / app 是常见的语言

  • 专门安装软件作为根用户(甚至是您的应用程序);仅在Dockerfile末尾切换到非root用户 USER

  • 不要尝试镜像任何特定系统的目录布局,用户名或数字用户ID;如果您尝试在其他地方运行该映像,则它们将不匹配

  • 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

如果您要扩展其他映像,则应该最好弄清楚它使用的用户名,并将固定的字符串放在派生映像的Dockerfile末尾的 USER 目录中。

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.

这篇关于我可以在Dockerfile中创建一个临时变量并在以后重用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆