如何防止 AWS Fargate 容器定义命令中的变量 substitution/expension

How can one prevent variable substitution/expension in AWS Fargate container definition command

在本地 运行ning docker 和 docker run 时,我传递了一些参数,例如:

docker run -p 8080:80 -e "SERVICE_B_URL=somehost.co.uk" -d mynginx:latest /bin/sh -c "envsubst '${SERVICE_B_URL}' < /etc/nginx/conf.d/default.template > /etc/nginx/conf.d/default.conf && exec nginx -g 'daemon off;'"

这很好用。在我的 /etc/nginx/conf.d/default.conf 中,字符串 ${SERVICE_B_URL} 被替换为 somehost.co.uk

当 运行在 AWS fargate 上使用如下定义时:

"environment": [
        {
          "name": "SERVICE_B_URL",
          "value": "someotherhost.co.uk"
        }
      ],
"command": [
        "/bin/sh",
        "-c",
        "envsubst '\${SERVICE_B_URL}' < /etc/nginx/conf.d/default.template > /etc/nginx/conf.d/default.conf && exec nginx -g 'daemon off;'"
      ],

\ 是为了转义 JSON 文件中的 \

当尝试 运行 时,容器因错误退出,因为 NGINX 正在查看文字字符串 ${SERVICE_B_URL}。当我检查容器并看到 AWS 用于启动容器的命令时,它是:

Command ["/bin/sh","-c","envsubst '\' < /etc/nginx/conf.d/default.template > /etc/nginx/conf.d/default.conf && exec nginx -g 'daemon off;'"]

请注意,在将字符串 '\${SERVICE_B_URL}' 作为命令提供给 docker 运行 之前,Fargate 已尝试对其进行扩展。我的意图是将其指定为文字字符串。

有没有办法逃避this/stop扩展。我试过 '\\${SERVICE_B_URL}' -> '\'.


脚注,如果您想知道为什么我将 '${SERVICE_B_URL}' 指定为 envsubst 而不是仅使用:

docker run -p 8080:80 -e "SERVICE_B_URL=somehost.co.uk" -d mynginx:latest /bin/sh -c "envsubst < /etc/nginx/conf.d/default.template > /etc/nginx/conf.d/default.conf && exec nginx -g 'daemon off;'"

原因是,被替换的文件包含其他 NGINX 配置,这些配置使用具有 $ 语法的变量。因此,为了防止这些被 envsubst 替换,我明确命名了我想要替换的变量。 运行 在本地使用 docker 运行,效果很好...

我最终通过使用 CMD 将要传递给 docker rundocker run 部分的命令简化了这一点,例如:

CMD ["/bin/sh","-c","envsubst '\${SERVICE_B_URL}' < /etc/nginx/conf.d/default.template > /etc/nginx/conf.d/default.conf && exec nginx -g 'daemon off;'"]

现在我们可以从 Fargate 的 JSON 文件中删除 command 配置。