![](/img/trans.png)
[英]How to use the same nginx.conf file for reverse proxy for docker-compose and kubernetes
[英]docker-compose --scale X nginx.conf configuration
我的nginx.conf文件当前有直接定义的路由:
worker_processes auto;
events { worker_connections 1024; }
http {
upstream wordSearcherApi {
least_conn;
server api1:61370 max_fails=3 fail_timeout=30s;
server api2:61370 max_fails=3 fail_timeout=30s;
server api3:61370 max_fails=3 fail_timeout=30s;
}
server {
listen 80;
server_name server_name 0.0.0.0;
location / {
proxy_pass http://wordSearcherApi;
}
}
}
有没有办法在docker-compose.yml中创建一个服务,当docker docker-compose up --scale api=3
,nginx会自动进行负载均衡吗?
你的当前配置是不可能的,因为它是静态的。 你有两个选择 -
1.使用docker engine swarm模式 - 您可以定义副本和swarm内部DNS将自动平衡这些副本上的负载。
参考 - https://docs.docker.com/engine/swarm/
2.使用着名的Jwilder nginx代理 - 此图像侦听docker套接字,使用GO中的模板在向上或向下扩展容器时动态更改nginx配置。
参考 - https://github.com/jwilder/nginx-proxy
在Nginx中可以实现动态上游(正常,sans Plus),但有技巧和限制。
你放弃了upstream
指令并使用plain proxy_pass
。
它提供循环负载平衡和故障转移,但没有指令的额外功能,如权重,故障模式,超时等。
必须通过变量将上游主机名传递给proxy_pass
,并且必须提供resolver
。
它迫使Nginx重新解析主机名(针对Docker网络的DNS)。
您将丢失与尾部斜杠相关的location
/ proxy_pass
行为。
在问题中反向代理裸/
喜欢的情况下,无关紧要。 否则,您必须手动rewrite
路径(请参阅下面的参考资料)。
让我们看看它是如何工作的。
泊坞窗,compose.yml
version: '2.2'
services:
reverse-proxy:
image: nginx:1.15-alpine
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf
ports:
- 8080:8080
app:
# A container that exposes an API to show its IP address
image: containous/whoami
scale: 4
nginx.conf
worker_processes 1;
events {
worker_connections 1024;
}
http {
access_log /dev/stdout;
error_log /dev/stderr;
server {
listen 8080;
server_name localhost;
resolver 127.0.0.11 valid=5s;
set $upstream app;
location / {
proxy_pass http://$upstream:80;
}
}
}
然后...
docker-compose up -d
seq 10 | xargs -I -- curl -s localhost:8080 | grep "IP: 172"
...生成如下所示的内容,表示请求分布在4个app
容器中:
IP: 172.30.0.2
IP: 172.30.0.2
IP: 172.30.0.3
IP: 172.30.0.3
IP: 172.30.0.6
IP: 172.30.0.5
IP: 172.30.0.3
IP: 172.30.0.6
IP: 172.30.0.5
IP: 172.30.0.5
参考文献:
Traefik直接依赖Docker API,可能是一个更简单,更可配置的选项。 让我们看看它的实际效果。
泊坞窗,compose.yml
version: '2.2'
services:
reverse-proxy:
image: traefik
# Enables the web UI and tells Traefik to listen to docker
command: --api --docker
ports:
- 8080:80
- 8081:8080 # Traefik's web UI, enabled by --api
volumes:
# So that Traefik can listen to the Docker events
- /var/run/docker.sock:/var/run/docker.sock
app:
image: containous/whoami
scale: 4
labels:
- "traefik.frontend.rule=Host:localhost"
然后...
docker-compose up -d
seq 10 | xargs -I -- curl -s localhost:8080 | grep "IP: 172"
...还会生成一些输出,指示请求分布在4个app
容器中:
IP: 172.31.0.2
IP: 172.31.0.5
IP: 172.31.0.6
IP: 172.31.0.4
IP: 172.31.0.2
IP: 172.31.0.5
IP: 172.31.0.6
IP: 172.31.0.4
IP: 172.31.0.2
IP: 172.31.0.5
在Traefik UI(示例中为http://localhost:8081/dashboard/
)中,您可以看到它识别了4个app
容器:
参考文献:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.