docker使用环境变量的方式动态配置nginx

一、需求二、制作镜像2.1 准备nginx.tmplate模板文件2.2 准备Dockerfile2.3 执行Dockerfile

三、启动nginx3.1 准备docker-compose.yml

四、补充4.1 关于nginx容器内配置文件的管理问题

一、需求

使用docker部署nginx时,由于nginx配置文件里面的一些ip和端口是随着环境变化而改变的,即在不同的环境里,使用的ip和端口都不一样。这就导致每次部署到新环境时,都要重新编写配置文件,再制作成新的镜像,比较繁琐。

所以我想要制作一个通用的镜像,将ip和端口设置成变量,等到需要部署到其他环境时候,再相应地传入ip和端口变量值

参考文章: 使用docker环境变量动态配置nginx

二、制作镜像

2.1 准备nginx.tmplate模板文件

nginx.tmplate文件内容如下:

server{

listen 80;

server_name localhost;

auth_basic "请输入账号密码";

auth_basic_user_file /usr/share/nginx/htpasswd; # 存放密码文件的路径

location / {

root /usr/share/nginx/html/;

index index.html;

}

location /skywalking/graphql {

proxy_method POST;

proxy_pass http://${SKYWALKING_SERVER_IP}:${SKYWALKING_SERVER_PORT}/graphql;

# 此处的两个变量为容器启动时传入

}

location /skywalking {

alias /usr/share/nginx/dist/;

try_files $uri $uri/ /skywalking/index.html;

}

error_page 500 502 503 504 /50x.html;

location = /50x.html {

root /usr/share/nginx/html;

}

}

其中${SKYWALKING_SERVER_IP}和${SKYWALKING_SERVER_PORT}两个变量是根据环境变化而变化的

2.2 准备Dockerfile

# 1.继承基础nginx镜像

FROM nginx:1.21.5

RUN \

ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && \

echo "Asia/Shanghai" > /etc/timezone

# 2.将准备的模板文件拷贝到容器的配置文件目录

COPY ./deploy/nginx.template /etc/nginx/conf.d

# 3. 切换工作目录

WORKDIR /etc/nginx/conf.d

# 4. 添加环境变量的写入

ENTRYPOINT envsubst '$SKYWALKING_SERVER_IP $SKYWALKING_SERVER_PORT' < nginx.template > default.conf && cat default.conf && nginx -g 'daemon off;'

EXPOSE 80

envsubst '$SKYWALKING_SERVER_IP $SKYWALKING_SERVER_PORT' < nginx.template > default.conf命令作用:

取环境变量$SKYWALKING_SERVER_IP和$SKYWALKING_SERVER_PORT的值注入到模板文件 nginx.template相应的位置,(所以此处变量名要和模板文件中保持一致)将替换好的模板内容输出到default.conf文件

envsubst命令使用参考: https://blog.csdn.net/kozazyh/article/details/107905080

cat default.conf命令作用: 查看生成的defual.conf文件内容。方便后续容器启动的时候,直接使用docker logs命令查看

2.3 执行Dockerfile

执行命令docker build -t nginx-test:9.3.0 .,制作出镜像nginx-test:9.3.0

三、启动nginx

3.1 准备docker-compose.yml

docker-compose.yaml内容如下:

version: '3.1'

services:

nginx:

image: nginx-test:9.3.0 # 镜像名称

container_name: nginx # 容器名字

restart: "no" # 开机自动重启

ports: # 端口号绑定(宿主机:容器内)

- '5080:80'

environment:

- SKYWALKING_SERVER_IP=47.106.225.35 #传入的变量值

- SKYWALKING_SERVER_PORT=12800 #传入的变量值

执行命令:docker-compose up -d启动。

四、补充

4.1 关于nginx容器内配置文件的管理问题

参考文章: https://www.cnblogs.com/fps2tao/p/9958009.html

推荐文章

评论可见,请评论后查看内容,谢谢!!!评论后请刷新页面。