前言
Nginx是一款面向性能設計的HTTP服務器,相較于Apache、lighttpd具有占有內存少,穩定性高等優勢。
由于現在需要部署nginx的docker,希望nginx配置文件里面有關server_name在啟動容器前動態修改。
但是由于nginx的配置文件不支持使用環境變量。網上找了好些方案,最終選擇使用envsubst
的方式改寫nginx配置文件。
工作原理
Nginx由內核和模塊組成,其中,內核的設計非常微小和簡潔,完成的工作也非常簡單,僅僅通過查找配置文件將客戶端請求映射到一個location block(location是Nginx配置中的一個指令,用于URL匹配),而在這個location中所配置的每個指令將會啟動不同的模塊去完成相應的工作。
Nginx的模塊從結構上分為核心模塊、基礎模塊和第三方模塊:
核心模塊:HTTP模塊、EVENT模塊和MAIL模塊
基礎模塊:HTTP Access模塊、HTTP FastCGI模塊、HTTP Proxy模塊和HTTP Rewrite模塊,
第三方模塊:HTTP Upstream Request Hash模塊、Notice模塊和HTTP Access Key模塊。
學習envsubst
envsubst就是將環境變量替換文件里面指定標記的值。
例如有如下文件env.conf
,內容如下
[test]
ip = ${ip}
port = ${port}
url = http://${ip}:${port}/index.html
phone = ${phone}
當執行export ip=192.168.1.5
,export port=8081
,export phone=13522223334
寫入環境變量。
然后執行envsubst < env.conf > env.new.conf
,就可以生成如下的env.new.conf
[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
文件如下
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
文件內容如下
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
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容器內部配置文件。大功告成!
以上就是nginx配置文件使用環境變量的詳細內容,更多關于nginx環境變量的資料請關注腳本之家其它相關文章!