【docker-compose】【nginx】动态配置

需求:部署前端镜像时需要动态修改nginx反向代理的后端服务的ip地址

  1. 原.conf配置调整,改为嵌入变量的文件模版
  2. Dockerfile 修改,通过envsubst将换将变量注入模版后再运行nginx
  3. docker-compose配置,通过environment动态修改变量

default.conf.tmplate(原default.conf)

动态变量:${MY_IP}

server {
    listen       80;
    server_name  localhost;

    location / {
      root   /usr/share/nginx/html;
      try_files $uri /index.html;
    }

    location /api{
      proxy_pass http://${MY_IP}:18892;
    }
    
}

Dockerfile

如果有多个变量可用逗号隔开,envsubst '$MY_IP,$MY_PORT'

FROM nginx:1.20.2-alpine

COPY dist /usr/share/nginx/html

COPY nginx.conf /etc/nginx/nginx.conf
# 拷贝模板
COPY default.conf.tmplate  /etc/nginx/conf.d
# 切换目录
WORKDIR /etc/nginx/conf.d
# 将环境变量注入模版
ENTRYPOINT envsubst '$MY_IP'  < default.conf.tmplate > default.conf && cat default.conf && nginx -g 'daemon off;'

EXPOSE 80

docker-compose.yml

注意environment下的变量名称MY_IP要与上述对应

environment:
      - MY_IP=server2

yml完整配置示例:
通过同一套镜像部署两个web项目,后端对应不同的数据库,前端对应不同的后端

version: '2'
networks:
  myapp:
    driver: bridge
services:
  server1:
    image: [ip]:5000/server
    container_name: server1
    restart: always
    environment:
      - spring.datasource.url=jdbc:mysql://[ip]:3306/dbs1?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=CTT
      - JAVA_OPTS=-Dlog4j2.formatMsgNoLookups=true
    networks:
      - myapp
  front1:
    image: [ip]:5000/front
    container_name: front1
    restart: always
    environment:
      - MY_IP=server1
    depends_on:
      - server1
    links:
      - server1
    ports:
      - "8095:80"
    networks:
      - myapp
  server2:
    image: [ip]:5000/server
    container_name: server2
    restart: always
    environment:
      - spring.datasource.url=jdbc:mysql://[ip]:3306/dbs2?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=CTT
      - JAVA_OPTS=-Dlog4j2.formatMsgNoLookups=true
    networks:
      - myapp
  front2:
    image: 10.1.58.6:5000/front
    container_name: front2
    restart: always
    environment:
      - MY_IP=server2
    depends_on:
      - server2
    links:
      - server2
    ports:
      - "8096:80"
    networks:
      - myapp

你可能感兴趣的:(运维,nginx,docker)