本地速率限制

速率限制用於控制網路介面控制器發送或接收的請求速率,這有助於防止 DoS 攻擊和限制網路爬蟲。

Envoy 支援本地(非分散式)和全域速率限制,以及兩種本地速率限制類型

此沙盒提供了 L4 連線速率限制的範例。

步驟 1:啟動所有容器

切換到 examples/local_ratelimit 目錄並啟動 docker 組合。

$ pwd
envoy/examples/ratelimit
$ docker compose pull
$ docker compose up --build -d
$ docker compose ps
Name                        Command                          State   Ports
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
ratelimtit_envoy-stat_1     /docker-entrypoint.sh /usr ...   Up      0.0.0.0:10000->10000/tcp,:::10000->10000/tcp, 0.0.0.0:9901->9901/tcp,:::9901->9901/tcp, 0.0.0.0:9902->9902/tcp,:::9902->9902/tcp
ratelimtit_service_1        /docker-entrypoint.sh ngin ...   Up      80/tcp

步驟 2:測試上游服務的速率限制

沙盒配置了 10000 埠以用於上游服務。

如果請求達到速率限制,Envoy 會新增 x-local-rate-limit 標頭,並拒絕連線,回應 429 HTTP 回應代碼和 local_rate_limited 內容。

現在,使用 curl 向受限上游服務發送五次請求

$ for i in {1..5}; do curl -si localhost:10000 | grep -E "x-local-rate-limit|429|local_rate_limited"; done
HTTP/1.1 429 Too Many Requests
x-local-rate-limit: true
local_rate_limited
HTTP/1.1 429 Too Many Requests
x-local-rate-limit: true
local_rate_limited
HTTP/1.1 429 Too Many Requests
x-local-rate-limit: true
local_rate_limited

前兩個請求會收到回應,其餘請求則會被拒絕,並帶有預期的回應。

步驟 3:測試 Envoy 統計資料的速率限制

沙盒配置了兩個埠,用於提供 Envoy 的管理介面和統計資料介面

  • 9901 顯示標準管理介面

  • 9902 顯示速率限制版本的管理介面

使用 curl 向埠 9901 上的無限統計資料發送五次請求,它不應包含任何速率限制回應

$ for i in {1..5}; do curl -si localhost:9901/stats/prometheus | grep -E "x-local-rate-limit|429|local_rate_limited"; done

現在,使用 curl 向受限統計資料發送五次請求

$ for i in {1..5}; do curl -si localhost:9902/stats/prometheus | grep -E "x-local-rate-limit|429|local_rate_limited"; done
HTTP/1.1 429 Too Many Requests
x-local-rate-limit: true
local_rate_limited
HTTP/1.1 429 Too Many Requests
x-local-rate-limit: true
local_rate_limited
HTTP/1.1 429 Too Many Requests
x-local-rate-limit: true
local_rate_limited

另請參閱

全域速率限制

Envoy 全域速率限制的參考文件。