如何在Dockerfile中正确读取环境变量

huangapple go评论76阅读模式
英文:

How to read enviroment variables in dockerfile correctly

问题

我有一个Dockerfile,我正在尝试读取运行时参数。以下是我的Dockerfile:

FROM clojure:openjdk-8-lein-slim-buster
ENV dbconfig ""
ENTRYPOINT ["java","-Ddbconfig=${dbconfig}", "-jar", "abc.jar", "server"]
EXPOSE 8080


这是Docker运行命令,我正在其中传递运行时值。我在这里做错了吗?值始终被识别为空。我还尝试过删除`ENV dbconfig ""`,但没有效果:

docker run --rm -e dbconfig='{"somekey" "value"}' xyz/abc

英文:

I have a Dockerfile where i am trying to read runtime args. Here is my dockerfile

FROM clojure:openjdk-8-lein-slim-buster
ENV dbconfig ""
ENTRYPOINT ["java","-Ddbconfig=${dbconfig}", "-jar", "abc.jar", "server"]
EXPOSE 8080

And here is the docker run command where i am passing values at runtime. Am i doing something wrong here? Values are always recognized as null. I have also tried removing ENV dbconfig "" but nothing works

docker run --rm -e dbconfig='{"somekey" "value"}' xyz/abc

答案1

得分: 1

你有两种方式来定义入口点:exec vs shell

exec形式被解析为JSON数组,这意味着你必须使用双引号(")而不是单引号(')。
所以你使用exec形式。

但是

与shell形式不同,exec形式不会调用命令shell。
这意味着不会发生正常的shell处理。例如,
ENTRYPOINT [ "echo", "$HOME" ] 不会对$HOME进行变量替换。

因此,为了允许环境变量替换,更倾向于使用shell形式:

ENTRYPOINT java -Ddbconfig=${dbconfig} -jar abc.jar server

或在exec形式中调用一个shell:

ENTRYPOINT [ "sh", "-c", "java", "-Ddbconfig=${dbconfig}", "-jar", "abc.jar", "server" ]
英文:

You have two ways to define entrypoint : exec vs shell.

> The exec form is parsed as a JSON array, which means that you must use
> double-quotes (“) around words not single-quotes (‘).
So you use the exec form.

But :

> Unlike the shell form, the exec form does not invoke a command shell.
> This means that normal shell processing does not happen. For example,
> ENTRYPOINT [ "echo", "$HOME" ] will not do variable substitution on
> $HOME

So favor the shell form to allow env variable substitutions :

ENTRYPOINT java -Ddbconfig=${dbconfig} -jar abc.jar server

or invoke a shell in the exec form :

ENTRYPOINT [ "sh", "-c", "java","-Ddbconfig=${dbconfig}", "-jar", "abc.jar", "server" ]

答案2

得分: -1

尝试使用CMD来传递运行时参数,示例如下:

ENTRYPOINT ["/bin/bash"]
CMD ["/sample.sh", "argument1", "argument2"]

然后在运行时传递参数的方式是:

docker run -i -t argument1 argument2
英文:

Try using CMD to pass runtime arguments, sample like below

ENTRYPOINT ["/bin/bash"]
CMD ["/sample.sh", "argument1","argument2"]

Then passing arguments at runtime would be:-

docker run -i -t argument1 argument2

huangapple
  • 本文由 发表于 2020年8月9日 14:40:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/63323240.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定