本文内容参考自《 自动的 Nginx 反向代理配置 》。
个人觉得:名字翻译成《自动化 Nginx 反向代理配置》更为贴切。
【一句话总结】
介绍了如何构建一个能够自动化配置 nginx 反向代理的方式。即将后端服务的部署与前端 nginx 的配置更改进行解耦。
【知识点】
- 对于 API 的使用者来说所有操作都是在同一个 URL 空间里进行的,而实际上是根据 URL 中不同的顶级“段”来进行路由的。
- 自动化配置的流程:当增加处理新“段”的 server 后,将投递一条 rabbitmq 消息(包含 Claim、ipAddress 和 PortNumber 信息),然后通过一个定制的组件 ProxyAutomation 消费 rabbitmq 消息,之后通过 SSH 和 SCP 重新 nginx 的配置,并促使配置的重新加载。
- SSH.NET 上有相关库。
...
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
keepalive_timeout 65;
include /etc/nginx/conf.d/*.conf;
}
下面这段配置是为了处理 host 为 api.example.com 端口为 80 的请求的。
include /etc/nginx/conf.d/api.example.com.conf.d/upstream.*.conf;
server {
listen 80;
server_name api.example.com;
include /etc/nginx/conf.d/api.example.com.conf.d/location.*.conf;
location / {
root /usr/share/nginx/api.example.com;
index index.html index.htm;
}
}
定制的 ProxyAutomation 组件就是通过将新 location.*.conf 文件放入 /etc/nginx/conf.d/api.example.com.conf.d/ 目录来实现添加新的 API “段” 的功能的。
例如需要增加 stock “段”,则要创建如下配置文件
location /stock/ {
proxy_pass http://stock;
}
这个配置就是让 nginx 将所有发向 api.example.com/stock/ 的请求代理到名字为 stock 的 upstream server 。这就用到了上面第一处 include 指令的配置内容(upstream.*.conf)。所以,我们定制的 ProxyAutomation 组件同样需要将新建的 upstream.stock.conf 文件放入 /etc/nginx/conf.d/api.example.com.conf.d/ 目录。upstream.stock.conf 文件内容可能如下
upstream stock {
server 10.0.0.23:8001;
server 10.0.0.23:8002;
}
这段配置用于将发向 api.example.com/stock/ 的请求以 round-robin 的方式发到两个地址上。