+-
在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文件的内容作为环境变量传递?

BTW:

--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"
        }
    }
}

任何帮助肯定是赞赏.

最佳答案
更新的答案

您提到在systemd单元文件中使用docker run命令.未在shell中启动系统化的ExecStart选项.名称支持环境变量替换.另见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 environmant变量将具有值{,并且docker run将假定“conf”为下一个参数(在本例中为图像名称).

解决方案:引用你的bash变量:

--env "TEMP_CONFIG=$(cat /etc/config.json)"

此外,如果您不需要,请不要使用猫:

--env "TEMP_CONFIG=$(</etc/config.json)"
点击查看更多相关文章

转载注明原文:在Docker中将JSON文件作为环境变量传递 - 乐贴网