首页 > 解决方案 > 无法在 Dockerfile 中替换 nginx 环境变量

问题描述

我在 nginx 的 docker build 期间将 REST API 的端点作为 env 变量传递,并且花了 6 个小时尝试大多数建议,但我已经没有足够的时间尝试了。

我要替换的 nginx conf:

location /my-api/ {
    proxy_pass  ${api_url}/;
}

我在 docker build 期间传递了这个值:

#base_url comes from system env 
docker build --build-arg base_api_url=$base_url

我在我的 Dockerfile 中得到了这个值:

ARG base_api_url
ENV  api_url=$base_api_url

# This prints the value
RUN echo "api_url= ${api_url}" . 

COPY package.json /usr/src/app/package.json
RUN npm install
COPY . /usr/src/app
RUN npm run build

FROM nginx:1.15.8-alpine
COPY --from=builder /usr/src/app/build /usr/share/nginx/html
EXPOSE 80

# this works
COPY nginx.conf /etc/nginx/nginx.conf.template

# Initially following code was building and deploying docker image and url was hard coded. it was working
# COPY nginx.conf /etc/nginx/conf.d/default.conf 
# Below will start the image but no REST endpoint configured
# CMD ["nginx", "-g", "daemon off;"]

# To substitute the api url few of the many things I have tried.
# Non of the below, have been able to replace the env api_url with its value 
# Actually I don't know -- since /etc/nginx/conf.d/default.conf is not replaced at all

# CMD /bin/bash -c "envsubst < nginx.conf > /etc/nginx/conf.d/default.conf && exec nginx -g 'daemon off;'"
# CMD /bin/sh -c "envsubst < nginx.conf > /etc/nginx/conf.d/default.conf && nginx -g 'daemon off;' || cat /etc/nginx/nginx.conf"

# Last status
CMD envsubst < /etc/nginx/nginx.conf.template > /etc/nginx/conf.d/default.conf && exec nginx -g 'daemon off;'

/etc/nginx/conf.d/default.conf 应该替换 api_url:

location /my-api/ {
    proxy_pass http://theApiURL;
}

我也尝试过像这样专门传递 env 变量:

CMD envsubst ${api_url} < /etc/nginx/nginx.conf.template > /etc/nginx/conf.d/default.conf && exec nginx -g 'daemon off;'

以及使用tee.

任何解决此问题的帮助/指导表示赞赏。

标签: dockernginx

解决方案


我通常在部署脚本中使用 sed 在 Dockerfile 之外执行此操作。

这是一个例子:

 #!/usr/bin/env bash
 # Deploys locally for dev work

 set -e
 export API_URL=www.theapiurl.com

 sed "s/api_url/${API_URL}/" nginx.conf.template > nginx.conf
 ...

 # run docker
 docker-compose build --no-cache
 docker-compose up -d

当然,您可以设置环境变量,但对您的用例有意义。我发现这种方法比 Docker 提供的任何方法都灵活得多。


推荐阅读