我想在 docker 运行期间将 JSON 文件的内容作为环境变量传递。 docker run 在 systemd 服务文件中初始化。
我做了类似的事情:
export TEMP_CONFIG=$(cat /etc/config.json)
并按如下方式运行 docker 容器:
docker run \
--env SERVICE_NAME=${CONTAINER_NAME} \
--env TEMP_CONFIG \
但是当我在 docker 容器内并尝试回显变量 ${TEMP_CONFIG} 它是空的。
root@ip-10-109-7-77:/usr/local/nginx/conf# echo ${TEMP_CONFIG}
root@ip-10-109-7-77:/usr/local/nginx/conf#
有没有办法将 JSON 文件的内容作为环境变量传递?
顺便提一句:
--env TEMP_CONFIG=$(cat /etc/config.json) \
执行上述操作会引发异常:
docker: Error parsing reference: "\"conf\"" is not a valid repository/tag.
config.json 的内容是:
{
"conf" :
{
"appname" :
{
"dbhost" : "xxxx",
"dbname" : "dbname",
"dbuser" : "user",
"dbpassword" : "xxxxx",
"hostname" : "xxxxxx"
},
"cacheBaseDir" : "/storage/",
"iccprofile" : "/etc/nginx/RGB.V1.0.icc",
"tmpDir" : "/tmp",
"mdb" :
{
"user" : "user",
"password" : "xxxxx",
"rights" : "GlobalAdministrator",
"company" : "somecompany"
}
}
}
任何帮助绝对不胜感激。
最佳答案
更新答案
您提到您使用 docker run
systemd 单元文件中的命令。一个系统 ExecStart
options 不是在 shell 中启动的。名称支持环境变量替换。另见 the documentation对此:
Basic environment variable substitution is supported. Use "
${FOO}
" as part of a word, or as a word of its own, on the command line, in which case it will be replaced by the value of the environment variable including all whitespace it contains, resulting in a single argument.
文档还说
StartExec
不在 shell 中执行:This syntax is intended to be very similar to shell syntax, but only the meta-characters and expansions described in the following paragraphs are understood. Specifically, redirection using "<", "<<", ">", and ">>", pipes using "|", running programs in the background using "&", and other elements of shell syntax are not supported. [...] Note that shell command lines are not directly supported.
但是,您可以使用
ExecStart
启动一个 shell,然后使用 -c
传递命令标志(您仍然需要引用我在下面的原始答案中提到的变量):ExecStart=/bin/bash -c "docker run -e \"TEMP_CONFIG=$(</etc/config.json)\" ..."
原答案
您的 JSON 字符串包含空格,并且不引用您的 shell 会将第一个空格之后的所有内容解释为后续参数。所以
TEMP_CONFIG=$(cat /etc/config.json)
本质上等同于:--env TEMP_CONFIG={ "conf" : { "...
在这种情况下,
TEMP_CONFIG
环境变量将具有值 {
, 和 docker run
将承担 "conf"
成为下一个参数(在本例中为图像名称)。解决方案:引用你的 bash 变量:
--env "TEMP_CONFIG=$(cat /etc/config.json)"
另外,不要使用
cat
当您不必:--env "TEMP_CONFIG=$(</etc/config.json)"
关于json - 在 Docker 中将 JSON 文件作为环境变量传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42444021/