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文件加載最新的數據。