nginx upstreamで502 Bad Gateway発生時に切り替える設定
nginxで502エラー発生時をヘルスチェック対象に追加する方法を解説します。proxy_next_upstreamによる502 Bad Gatewayの検知方法、max_failsやfail_timeoutの設定例、upstreamサーバーの自動切り替え手順まで紹介します。
環境
- OS CentOS Linux release 7.9.2009 (Core)
- nginx 1.18.0
nginx設定
proxy_next_upstreamに「http_502」を追加してあげます。
upstream app {
server バックエンドのIP1 max_fails=3 fail_timeout=30s;
server バックエンドのIP2 max_fails=3 fail_timeout=30s;
}
server {
listen 80;
server_name リバースプロキシ側のIP;
location / {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_pass http://app;
proxy_next_upstream error timeout http_502;
proxy_next_upstream_tries 0;
proxy_next_upstream_timeout 10;
proxy_connect_timeout 5s;
proxy_send_timeout 5s;
proxy_read_timeout 5s;
}
}これで、502エラー発生時もロードバランサーが切り替わるようになります。
【参考】
max_fails : 指定回数のアクセス不能だった場合、サーバがダウンしたと判断
fail_timeout : fail_timeoutに指定された時間だけupstreamから外れます
補足
nginxのオープンソース版では、パッシブヘルスチェックを利用してバックエンドサーバーの異常を検知できます。
特に、502 Bad Gatewayが発生した場合も異常として扱いたい場合は、proxy_next_upstreamへHTTPステータスコードを追加することで、別のupstreamサーバーへ自動的に切り替えることが可能です。
proxy_next_upstream error timeout http_500 http_502 http_503 http_504;
proxy_next_upstream_tries 3;また、max_failsとfail_timeoutを組み合わせることで、一定回数エラーが発生したサーバーを一時的に負荷分散対象から除外できます。
upstream backend {
server app01:8080 max_fails=3 fail_timeout=30s;
server app02:8080 max_fails=3 fail_timeout=30s;
}なお、nginx OSSでは実際のリクエストを利用したパッシブヘルスチェックのみ利用できます。定期的なアクティブヘルスチェックが必要な場合は、NGINX Plusや外部モジュールの導入も検討してみてください。
参考リンク
- NGINX公式ドキュメント(ngx_http_upstream_module)
- NGINX Documentation(HTTP Health Checks)
- NGINX公式ドキュメント(proxy_next_upstream)
関連記事
-
前の記事
C# フォルダを作成する 2021.01.17
-
次の記事
javascript faviconを変更する 2021.01.18
コメントを書く