json - 在 Docker 中将 JSON 文件作为环境变量传递

我想在 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)"

https://stackoverflow.com/questions/42444021/

相关文章:

opencv - OpenCV中两个矩阵的广义特征值

image - 颜色键在图像处理中的作用是什么?

opencv - OpenCV || matchShapes findContours断言失败

opencv - mac上opencv2.3.1中 undefined symbol ,cvSmoo

android - 使用 OpenCV 在 Android 中将 4 channel 矩阵转换为 1

visual-studio-2008 - 应用程序无法启动:VS中的OpenCV x64编译使用x8

c# - DLL 'cvCreateContourTree'中的 'opencv_imgproc23

opencv - 用opencv实现消失点算法

image-processing - cvCalculateOpticalFlowFarneback

docker - 如何使用非 root 用户权限构建 docker 以使用 pipenv 设置 py