需求:部署前端镜像时需要动态修改nginx反向代理的后端服务的ip地址
- 原.conf配置调整,改为嵌入变量的文件模版
- Dockerfile 修改,通过envsubst将换将变量注入模版后再运行nginx
- 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: '3'
services:
server1:
image: 127.0.0.1:5000/server
container_name: server1
restart: always
front1:
image: 127.0.0.1:5000/front
container_name: front1
restart: always
environment:
- MY_IP=server1
depends_on:
- server1
ports:
- "8080:80"
server2:
image: 127.0.0.1:5000/server
container_name: server2
restart: always
front2:
image: 127.0.0.1:5000/front
container_name: front2
restart: always
environment:
- MY_IP=server2
depends_on:
- server2
ports:
- "8081:80"