服务器之家:专注于服务器技术及软件下载分享
分类导航

云服务器|WEB服务器|FTP服务器|邮件服务器|虚拟主机|服务器安全|DNS服务器|服务器知识|Nginx|IIS|Tomcat|

服务器之家 - 服务器技术 - Nginx - nginx配置文件使用环境变量的操作方法

nginx配置文件使用环境变量的操作方法

2021-08-06 17:36janbar Nginx

Nginx是一款开源代码的高性能HTTP服务器和反向代理服务器,同时支持IMAP/POP3/SMTP代理服务,相较于Apache、lighttpd具有占有内存少,稳定性高等优势,所以深受用户喜爱,今天小编给大家分享nginx配置文件使用环境变量的操作方法,感

前言

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,内容如下

?
1
2
3
4
5
[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

?
1
2
3
4
5
[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文件如下

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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文件内容如下

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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环境变量的资料请关注服务器之家其它相关文章!

原文链接:https://www.cnblogs.com/janbar/archive/2021/06/01/14838474.html

延伸 · 阅读

精彩推荐