在nginx的docker构建期间,我正在传递REST API的端点作为环境变量,并且花了6个小时尝试了大多数建议,我已经没有耐心去尝试了。
nginx conf,我用它替换:
location /my-api/ {
proxy_pass ${api_url}/;
}
我在docker构建过程中传递了这个值:
#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
。
任何帮助/指导来解决这个问题的人都将不胜感激。
发布于 2019-05-07 21:43:48
我通常在Dockerfile之外使用sed在部署脚本中执行此操作。
下面是一个例子:
#!/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提供的任何东西都灵活得多。
https://stackoverflow.com/questions/56030655
复制相似问题