在nginx的docker构建过程中,我将REST API的端点作为env变量传递,并花了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;
}
我也尝试过专门传递环境变量,例如:
CMD envsubst ${api_url} < /etc/nginx/nginx.conf.template > /etc/nginx/conf.d/default.conf && exec nginx -g 'daemon off;'
以及使用tee
之类的变体。
感谢任何帮助/指导来解决此问题。
答案 0 :(得分:0)
我通常在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提供的任何方法都要灵活得多。