动态管理upsteam---nginx_http_dyups_module
nginx_http_dyups_module
nginx_http_dyups_module是第三方开源软件,它提供API动态修改upstream的配置,并且支持Nginx的ip_hash、keepalive等与upstream有关的配置。
安装nginx_http_dyups_module
git clone git://github.com/yzprofile/ngx_http_dyups_module.git
./configure --add-module=../ngx_http_dyups_module
动态管理upstream
upstream myapp_01 { server 10.102.20.20:80; } upstream myapp_02 { server 10.102.20.211:80; } server { listen 8000; location / { allow 127.0.0.1; deny all; dyups_interface; } } server { listen 80; server_name localhost; location / { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; set $ups myapp; proxy_pass http://$ups; } }
确认目前的upstream清单中是否有myapp
[root@lua conf]# curl http://127.0.0.1:8000/list myapp_01 myapp_02
上面的输出显示没myapp,下面添加upsteam,并命名为myapp(它是以覆盖当前upstream的内容完成配置的):
[root@lua conf]# curl -d "server 10.102.20.20:80 max_fails=3 fail_timeout=5s weight=10 ;server 10.102.20.211 max_fails=3 fail_timeout=5s weight=10;" 127.0.0.1:8000/upstream/myapp success
获取upsteam清单的详情:
[root@lua conf]# curl 127.0.0.1:8000/detail myapp_01 server 10.102.20.20:80 weight=1 max_conns=0 max_fails=1 fail_timeout=10 backup=0 down=0 myapp_02 server 10.102.20.211:80 weight=1 max_conns=0 max_fails=1 fail_timeout=10 backup=0 down=0 myapp server 10.102.20.20:80 weight=10 max_conns=0 max_fails=3 fail_timeout=5 backup=0 down=0 server 10.102.20.211:80 weight=10 max_conns=0 max_fails=3 fail_timeout=5 backup=0 down=0
访问upsteam下的服务,结果显示正常
[root@lua conf]# curl -I 10.102.20.103 HTTP/1.1 200 OK Server: nginx/1.14.2 Date: Fri, 13 Dec 2019 01:55:39 GMT Content-Type: text/html; charset=utf-8 Content-Length: 616 Connection: keep-alive Last-Modified: Fri, 14 Dec 2018 09:10:04 GMT ETag: "5c13736c-268" Accept-Ranges: bytes
验证删除节点功能:
curl -i -X DELETE 127.0.0.1:8000/upstream/myapp HTTP/1.1 200 OK Server: nginx/1.14.2 Date: Fri, 13 Dec 2019 01:57:43 GMT Content-Length: 7 Connection: keep-alive success
可以看到已删除myapp
[root@lua conf]# curl http://127.0.0.1:8000/list myapp_01 myapp_02
进行压力测试,与原生的Nginx upstream配置相比,没有明显的性能波动,稳定性正常,upstream的动态添加和删除操作会随机执行。
dyups支持的接口说明表:
请求方法 | HTTP接口 | 用途 |
GET | /detail | 获取所有upsteam的清单明细 |
GET | /list | 获取所有upsteam的name |
GET | /upstream/name | 获取指定的upstream内的后端服务器的IP地址和端口 |
POST | /upstream/name | 覆盖指定的upstream的内容,包括IP地址、端口号、权重等信息 |
DELETE | /upstream/name | 删除指定的upstream |
功能验证完成后,准备灰度发布。
此模块还提供了Ngx_Lua接口,方便Ngx_Lua处理动态的upstream,可参考官方的Wiki。https://github.com/yzprofile/ngx_http_dyups_module/blob/master/README.md
确保upstream数据的完整性
使用 nginx_http_dyups_module时有一个隐患,即动态修改的配置存放在Nginx内存中的,如果重载Nginx配置,这些数据就会丢失。
对此可行的解决方案是开发一个脚本,用来调用nginx_http_dyups_module的接口/detail,获取upstream的全部信息,并存为Nginx可以读取的upstream配置文件;
在upstream发生变更时就会触发该脚本生成一个upstream文件,将这个文件include到Nginx配置中;
当Nginx重载配置时,它会先从这个upstream文件加载最新的数据。