12_docker-compose动态修改nginx配置文件

docker-compose动态修改nginx配置文件

目录

docker-compose动态修改nginx配置文件

一、目录结构

二、docker-compose.yml编写

三、配置文件编写(.env、nginx.template)

四、启动服务

五、验证配置

六、注意


一、目录结构

apps
    │
    ├── .env # 配置文件
    │
    ├── docker-compose.yml
    │
    └── conf 
          │
          └── nginx
           │
           └── nginx.template

二、docker-compose.yml编写

# vim docker-compose.yml
version: "2"
services:
  web:
    image: nginx:1.19.9-alpine
    restart: always
    ports:
    - 80:80
    volumes:
    - ./conf/nginx:/etc/nginx
    environment:
     - BACKEND_HOSTS=${backend_hosts}
    command:
    - /bin/sh
    - -c
    - "envsubst '$${BACKEND_HOSTS}' \
       </etc/nginx/nginx.template> \
       /etc/nginx/nginx.conf && exec nginx -g 'daemon off;'"

三、配置文件编写(.env、nginx.template)

  1、env

#.env
backend_hosts=172.19.12.188:8080

  2、nginx.template

# nginx.template
worker_processes  1;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    server {
        listen       80;
        location / {
            proxy_pass http://${BACKEND_HOSTS};
        }   
    }  
}

四、启动服务

[root@localhost nginx]# docker-compose up -d
Creating network "nginx_default" with the default driver
Creating nginx_web_1 ... done

五、验证配置

[root@localhost nginx]# cd conf/nginx/
[root@localhost nginx]# ls
nginx.conf  nginx.template
# vim nginx.conf
worker_processes  1;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    server {
        listen       80;
        location / {
            proxy_pass http://172.19.12.188:8080;
        }
    }
}

${BACKEND_HOSTS}变量已经被动态修改为IP地址

六、注意

1、动态修改配置是使用Linux 【envsubst】命令动态替换配置语法:【envsubst < original_file > destination_file】、【envsubst $args1,$args2 < original_file > destination_file】

2、”$${BACKEND_HOSTS}“ 中第一个$为docker-compose转义字符

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

主公不搬砖

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值