Nginxのプロキシ機能は、バックエンドサーバーが停止していると502(Bad Gateway)を応答する仕様のようです。Bad Gatewayは「ゲートウェイ/プロキシとして動作しているサーバ(Nginx)が、要請の履行を試みているときに,自身がアクセスした内方サーバ(バックエンドサーバー)から妥当でない応答を受信した。」という定義なので、動きとしては正しいそうです。
ただし、このようなケースでは、503(Service Unavailable)を返却したいと思うエンジニアの方も結構いるのではないでしょうか?
特にApacheのプロキシ機能(mod_proxy)を使っていたエンジニアの方は、503(Service Unavailable)になるものと決めつけているかもしれません・・・というか、私がその一人でした
$ curl -D - http://localhost:18080/spring-boot/
HTTP/1.1 502 Bad Gateway
Server: nginx
Date: Tue, 12 Jul 2016 07:02:31 GMT
Content-Type: text/html
Content-Length: 537
Connection: keep-alive
ETag: "56a7852a-219"
<!DOCTYPE html>
<html>
<head>
<title>Error</title>
<style>
body {
width: 35em;
margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif;
}
</style>
</head>
<body>
<h1>An error occurred.</h1>
<p>Sorry, the page you are looking for is currently unavailable.<br/>
Please try again later.</p>
<p>If you are the system administrator of this resource then you should check
the <a href="http://nginx.org/r/error_log">error log</a> for details.</p>
<p><em>Faithfully yours, nginx.</em></p>
</body>
</html>
ってか503(Service Unavailable)にすべき?
これは議論がわかれるところな気がしますね。
個人的には、できるだけデフォルトの動き使うのが好きなので502のままでよい気がしているのですが、一方で微妙に内部の構成を外部に晒している感がある+利用者目線で考えると502(Bad Gateway)より503(Service Unavailable)の方が直感的なエラーであることから、503(Service Unavailable)にしたい気もします(つまり、どっちつかずの優柔不断野郎です )
レスポンスコードを503(Service Unavailable)にしてみよう!!
503(Service Unavailable)派の方は、Nginxのエラーページ機能(error_page
ディレクティブ)を使ってレスポンスコードを変換することができます。
http {
server_tokens off;
server {
listen 18080;
server_name localhost;
location /spring-boot/ {
proxy_pass http://localhost:8080/;
error_page 502 =503 /50x.html; # 追加: 502を503に変換してエラーページ(`/50x.html`)をレスポンスする
}
# ...
}
}
Nginxを再起動した後にアクセスすると、以下のようなレスポンス
$ curl -D - http://localhost:18080/spring-boot/
HTTP/1.1 503 Service Temporarily Unavailable
Server: nginx
Date: Tue, 12 Jul 2016 06:57:01 GMT
Content-Type: text/html
Content-Length: 537
Connection: keep-alive
ETag: "56a7852a-219"
<!DOCTYPE html>
<html>
<head>
<title>Error</title>
<style>
body {
width: 35em;
margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif;
}
</style>
</head>
<body>
<h1>An error occurred.</h1>
<p>Sorry, the page you are looking for is currently unavailable.<br/>
Please try again later.</p>
<p>If you are the system administrator of this resource then you should check
the <a href="http://nginx.org/r/error_log">error log</a> for details.</p>
<p><em>Faithfully yours, nginx.</em></p>
</body>
</html>
まとめ
無理に503(Service Unavailable)にする必要はないと思います。何かしらの制約により503(Service Unavailable)を応答する必要がある場合は、本記事で紹介した方法が使えると思います。