抱歉,您的浏览器无法访问本站
本页面需要浏览器支持(启用)JavaScript
了解详情 >

通过docker构建nginx有一个较大的问题,就是无法方便修改nginx的conf配置,特别是其中proxy_pass地址,极有可能会经常变化,而每次变化都需要重新构建镜像显得极不优雅,因此本文将介绍如何通过环境变量来实现动态nginx的conf配置。

一、准备文件

1、ui.conf

nginx其实已支持读取环境变量的值,但需要通过template文件转换,此时为了vscode能够有语法提示,配置文件的名称仍然以.conf结尾。
其中通过${xxx}的写法,即可读取到环境变量

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
server {
listen ${LISTEN_PORT};
server_name ${SERVER_NAME};

gzip on;
gzip_static on;
gzip_min_length 1k;
gzip_comp_level 4;
gzip_proxied any;
gzip_types text/plain text/xml text/css;
gzip_vary on;
gzip_disable "MSIE [1-6]\.(?!.*SV1)";

location /webapi/ {
proxy_pass ${PROXY_PASS};
proxy_connect_timeout 15s;
proxy_send_timeout 15s;
proxy_read_timeout 15s;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto http;
}
location / {
root /html;
try_files $uri $uri/ /index.html;
}
}

2、Dockerfile

其中主要为通过ENV配置默认环境变量,其次将配置文件添加至镜像中nginx目录下的templates,并将文件名改为default.conf.template
当容器启动后,nginx会将模版文件转化为conf文件并放置于conf.d目录中

1
2
3
4
5
6
7
8
9
FROM nginx

COPY ./dist/ /html

ENV LISTEN_PORT=80\
SERVER_NAME=localhost\
PROXY_PASS=http://127.0.0.1

ADD ./ui.conf /etc/nginx/templates/default.conf.template

二、构建镜像

1.目录结构

  • root
    • ui.conf
    • Dockerfile
    • dist
      • index.html

2.构建镜像

在root目录中执行命令

1
docker build -t my-nginx:1.0 .

3、检验

此时通过docker run等运行镜像即可,例如通过docker swarm运行

1
2
3
4
5
6
7
8
9
version: '3.7'
services:
my-nginx:
image: my-nginx:1.0
environment:
# 指定环境变量
PROXY_PASS: http://192.168.3.75:9898/
ports:
- 80:80

评论