若能与你化作星座,一起描绘星空中的梦想。|

janbar

园龄:4年5个月 粉丝:29 关注:10

2021-06-01 18:57 阅读 7609 评论 0 推荐 0

nginx配置文件使用环境变量

前言

由于现在需要部署nginx的docker,希望nginx配置文件里面有关server_name在启动容器前动态修改。
但是由于nginx的配置文件不支持使用环境变量。网上找了好些方案,最终选择使用envsubst的方式改写nginx配置文件。

学习envsubst

envsubst就是将环境变量替换文件里面指定标记的值。
例如有如下文件env.conf,内容如下

copy
[test] ip = ${ip} port = ${port} url = http://${ip}:${port}/index.html phone = ${phone}

当执行export ip=192.168.1.5export port=8081export phone=13522223334写入环境变量。
然后执行envsubst < env.conf > env.new.conf,就可以生成如下的env.new.conf

copy
[test] ip = 192.168.1.5 port = 8081 url = http://192.168.1.5:8081/index.html phone = 13522223334

还可以指定只替换部分环境变量,source env.env && envsubst '$ip;$phone' < env.conf,这样只会替换ip和phone这两个变量。
上面只替换部分环境变量,在Linux测试只能用单引号,用双引号无效,分隔符试过, . ; |这四种都可以,我估计还有更多分隔符。

应用nginx配置文件

docker-compose.yml文件如下

copy
version: "3" services: nginx: image: nginx:1.20.1-alpine container_name: nginx ports: - 80:80 - 443:443 environment: - NGINX_HOST=www.janbar.com - NGINX_PORT=80 volumes: - /root/janbar.temp:/etc/nginx/conf.d/janbar.temp command: /bin/sh -c "envsubst < /etc/nginx/conf.d/janbar.temp > /etc/nginx/conf.d/default.conf && exec nginx -g 'daemon off;'" network_mode: bridge restart: always

/root/janbar.temp文件内容如下

copy
server { listen ${NGINX_PORT}; listen [::]:${NGINX_PORT}; server_name ${NGINX_HOST}; location / { root /usr/share/nginx/html; index index.html index.htm; } error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; } }

按照上述docker-compose.yml配置文件最终生成docker容器里面的配置文件如下cat /etc/nginx/conf.d/default.conf

copy
server { listen 80; listen [::]:80; server_name www.janbar.com; location / { root /usr/share/nginx/html; index index.html index.htm; } error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; } }

总结

经过上述骚操作,最终可以通过环境变量的方式更新nginx的docker容器内部配置文件。大功告成!

posted @   janbar  阅读(7609)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· C++代码改造为UTF-8编码问题的总结
· DeepSeek 解答了困扰我五年的技术问题
· 为什么说在企业级应用开发中,后端往往是效率杀手?
阅读排行:
· 10亿数据,如何做迁移?
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 推荐几款开源且免费的 .NET MAUI 组件库
· 易语言 —— 开山篇
· Trae初体验

FAVOURITE

点击右上角即可分享
微信分享提示
*✧⁺˚⁺ପ(๑・ω・)੭ु⁾⁾ 好好学习天天向上
进入亮色模式
进入亮色模式

FAVOURITE