如何在 Dockerfile CMD 中使用变量? [英] How can I use a variable inside a Dockerfile CMD?

查看:124
本文介绍了如何在 Dockerfile CMD 中使用变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 Dockerfile 中:

Inside my Dockerfile:

ENV PROJECTNAME mytestwebsite
CMD ["django-admin", "startproject", "$PROJECTNAME"]

错误:

CommandError: '$PROJECTNAME' is not a valid project name

这里最快的解决方法是什么?Docker 有没有计划在以后的 Docker 版本中修复"或引入这个功能?

What is the quickest workaround here? Does Docker have any plan to "fix" or introduce this functionality in later versions of Docker?

注意:如果我从 Docker 文件中删除 CMD 行,然后运行 ​​Docker 容器,我可以从容器内部手动运行 Django-admin startproject $PROJECTNAME,它将创建项目...

NOTE: If I remove the CMD line from the Docker file and then run the Docker container, I am able to manually run Django-admin startproject $PROJECTNAME from inside the container and it will create the project...

推荐答案

当您使用执行列表时,例如...

When you use an execution list, as in...

CMD ["django-admin", "startproject", "$PROJECTNAME"]

...然后 Docker 将直接执行给定的命令,而不涉及 shell.由于不涉及外壳,这意味着:

...then Docker will execute the given command directly, without involving a shell. Since there is no shell involved, that means:

  • 无变量扩展
  • 无通配符扩展
  • 没有使用 ><| 等进行 I/O 重定向
  • 没有通过 command1 的多个命令;命令2
  • 等等.
  • No variable expansion
  • No wildcard expansion
  • No i/o redirection with >, <, |, etc
  • No multiple commands via command1; command2
  • And so forth.

如果你想让你的CMD扩展变量,你需要安排一个shell.你可以这样做:

If you want your CMD to expand variables, you need to arrange for a shell. You can do that like this:

CMD ["sh", "-c", "django-admin startproject $PROJECTNAME"]

或者你可以使用一个简单的字符串而不是一个执行列表,这样你得到的结果与前面的例子基本相同:

Or you can use a simple string instead of an execution list, which gets you a result largely identical to the previous example:

CMD django-admin startproject $PROJECTNAME

这篇关于如何在 Dockerfile CMD 中使用变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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