在 CMD 中使用环境变量

我可以在 Dockerfile 的 CMD 节中使用环境变量吗?

我想这样做:

CMD ["myserver", "--arg=$ARG", "--memcache=$MEMCACHE_11211_TCP_ADDR:$MEMCACHE_11211_TCP_PORT"]

其中 $MEMCACHE _ 11211 _ TCP _ * 将通过包含 docker run命令的—— link 参数自动设置。$ARG 可以在运行时由用户配置,也许是通过“-e”参数?

这似乎对我不起作用,它似乎是字面上通过字符串“ $ARG”的例子。

67094 次浏览

I can't speak to how it is supposed to work, but I think if you called this as a shell script, e.g. CMD runmyserver.sh, then the interpretation of the shell variables would be deferred until the CMD actually ran.

So, try

myserver --arg=$ARG --memcache=$MEMCACHE_11211_TCP_ADDR:$MEMCACHE_11211_TCP_PORT``

as a shell script?

This answer may be a little late. But environment for CMD is interpreted slightly differently depending on how you write the arguments. If you pass the CMD as a string (not inside an array), it gets launched as a shell instead of exec. See https://docs.docker.com/engine/reference/builder/#cmd.

You may try the CMD without the array syntax to run as a shell:

CMD myserver --arg=$ARG --memcache=$MEMCACHE_11211_TCP_ADDR:$MEMCACHE_11211_TCP_PORT

Both Andys had it right. The json syntax bypasses the entrypoint. When you use CMD as in their example, it is considered as an argument to the default entrypoint: /bin/sh -c which will interpret the environement variables.

Docker does not evaluate the variables in CMD in either case. In the former, the command is directly called so nothing gets interpreted, in the later, the variables are interpreted by sh.

CMD ["sh", "-c", "echo ${MY_HOME}"]

Answer from sffits here.