2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Nginx / gunicorn】タイムアウト時間を変更する

Posted at

概要

Nginx と gunicorn を用いてデプロイ後、一部のページで「502 Bad Gateway」エラーが発生。。
とりあえず表示させたいので、タイムアウト時間を延ばして解決させました。

環境

Python 3.9
Django 3.2

解決方法

nginx.conf に一文追加する
gunicorn 再起動時、コマンドライン引数を追加する

手順

nginx.conf を編集する

sudo vi /etc/nginx/nginx.conf

状況に応じて下記を追加する (デフォルトは60秒です)

http{
   ...
   proxy_read_timeout 300;
   proxy_connect_timeout 300;
   proxy_send_timeout 300;
   ...
}

各設定値について

  • proxy_connect_timeout
    静的Webサーバ ( Nginx ) とアプリケーションサーバ ( gunicorn ) との接続タイムアウト秒数を指定
    アプリケーションサーバに接続要求を送り、n秒間接続できない場合に発生します
    つまり「n秒経っても TCPコネクション が確立できない場合にエラーを吐くよ」という設定

  • proxy_send_timeout
    静的Webサーバ ( Nginx ) からアプリケーションサーバ ( gunicorn ) へのデータ送出の接続タイムアウト秒数を指定
    つまり「TCPコネクション確立後、n秒経っても Nginx から gunicorn にリクエストを送信できない場合にエラーを吐くよ」という設定

  • proxy_read_timeout
    アプリケーションサーバ ( gunicorn ) から 静的Webサーバ ( Nginx ) へのデータ送出の接続タイムアウト秒数を指定
    つまり「TCPコネクション確立後、n秒経っても gunicorn から Nginx へのレスポンスを受信できない場合にエラーを吐くよ」という設定

私の場合、一部のページのみ「502 Bad Gateway」エラーが発生していたので、レスポンスの受信時間のみ延ばしたかったので下記のように設定しました

http{
   ...
   proxy_send_timeout 300;
   ...
}

nginx を再起動して設定ファイルを読み込んでもらう

sudo systemctl restart nginx

つづいて gunicorn を再起動 ( ※コマンドライン引数に --timeout を追加が必要です )

# 現在起動中の gunicorn のポート番号 (PID) を確認
ps aux | grep gunicorn

# 指定のポート番号 (PID) を kill
kill <PID>

# gunicorn を起動
gunicorn config.wsgi:application --timeout 300

gunicorn のタイムアウト時間のデフォルトは 30秒なので --timeout を追加してあげましょう

まとめ

無事 502 エラーが発生しなくなりました!
今後は速度改善に取り組みます。

参考記事

この備忘録は以下の情報を参考にさせていただきました。感謝です。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?