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;
    }

    # 其他配置...
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值