docker - 无法在 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
.
任何解决此问题的帮助/指导表示赞赏。
解决方案
我通常在部署脚本中使用 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 提供的任何方法都灵活得多。
推荐阅读
- c - Node.js 接受请求,形成 2xx 响应,但响应状态码为 400
- c# - 根据分隔符从现有列表创建较小的列表
- android - Recyclerview 字母滚动条
- sql - Oracle SQL 重用用户输入
- python-3.x - 手动添加成本会导致 MissingDataError
- python - 如何在 Python 的列表推导下使用 if 和 else 语句从数字列表中列出奇数和偶数?
- python - 从 html 请求中提取特定行到变量中
- matrix - 如何从具有聚合的单个表中使用 DAX 在功率 bi 矩阵中创建排名
- android - 检测是否在 androidx 生物识别库中添加或删除了新的指纹
- java - Spring Boot 中 YAML 处理器(Jackson、SnakeYAML)的值转换错误