nginx配置文件使用環境變量


前言

由於現在需要部署nginx的docker,希望nginx配置文件里面有關server_name在啟動容器前動態修改。
但是由於nginx的配置文件不支持使用環境變量。網上找了好些方案,最終選擇使用envsubst的方式改寫nginx配置文件。

學習envsubst

envsubst就是將環境變量替換文件里面指定標記的值。
例如有如下文件env.conf,內容如下

[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

[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容器內部配置文件。大功告成!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM