如何在Dockerfile CMD中使用变量? [英] How can I use a variable inside a 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重定向c $ c> | 等 - 没有通过
command1的多个命令; command2
- 依此类推。
- 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屋!