nginx模板配置
背景
nginx通过读取环境变量完成对nginx.conf的相关代理设置,但是nginx.conf不支持直接读取环境变量、所以使用nginx的模板功能达到相应目的
带有环境变量的 Nginx 配置文件模板。在 Docker 化部署 Nginx 时,为了能够通过环境变量动态地更改 Nginx 的配置,经常会引入这个模板文件。Docker 启动后会读取环境变量,替换掉 default.conf.template 中使用的环境变量,生成 default.conf,然后再启动 Nginx。
模板文件
server {
listen ${PORT};
server_name localhost;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
location /api {
proxy_pass ${PROXY_URL};
rewrite ^/api/(.*)$ /$1 break;
}
# 其他配置...
}
nginx.conf
通过 include /etc/nginx/conf.d/*.conf;
引用所有配置文件
# nginx.conf
user root;
worker_processes auto;
error_log logs/error.log;
events {
use epoll;
worker_connections 65535;
}
http {
include mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for" $request_time';
access_log logs/access.log main;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
#gzip on;
include /etc/nginx/conf.d/*.conf; # 引用 conf.d 目录下的所有 .conf 文件
}
容器验证
修改docker-compose并添加模板文件所需的环境变量PROXY_URL、PORT
version: '2.1'
services:
nginx:
container_name: nginx
restart: always
image: nginx
ports:
- 80:80
- 443:443
environment:
TZ: "Asia/Shanghai"
PROXY_URL: http://127.0.0.1/8890
PORT: 9999
volumes:
- /home/nginx/data/conf.d:/etc/nginx/conf.d
- /home/nginx/data/log:/var/log/nginx
- /home/nginx/conf/nginx.conf:/etc/nginx/nginx.conf
- /home/nginx/templates:/etc/nginx/templates
- /usr/local/myApp:/usr/share/nginx/html
将模板文件放在/home/nginx/templates下并修改名字为test2.conf.template
server {
listen ${PORT};
server_name localhost;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
location /api {
proxy_pass ${PROXY_URL};
rewrite ^/api/(.*)$ /$1 break;
}
# 其他配置...
}
进入容器内部可看到/etc/nginx/conf.d下生成了test2.conf
内容如下:
环境变量占位符均被替换
server {
listen 9999;
server_name localhost;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
location /api {
proxy_pass http://127.0.0.1/8890;
rewrite ^/api/(.*)$ /$1 break;
}
# 其他配置...
}