0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

中級編:NginxでFlaskアプリをリバースプロキシ構成する方法

Last updated at Posted at 2025-08-13

中級編:Nginxでリバースプロキシ構成(Flask編)

🎯 目的

  • Nginxをリバースプロキシとして構成し、バックエンドのアプリケーション(Flask)と連携させる。
  • Webブラウザからアクセスした際、Nginx経由でFlaskアプリが応答する状態を構築する。

✅ 前提条件

  • Nginxがインストール済み・起動中であること(CentOSを想定)
  • Python 3.x、Flaskがインストール済み
python3 --version
python3 -m flask --version
  • ファイアウォールで必要なポート(80番など)が許可されていること

🧱 ステップ1:Flaskバックエンドの作成

Flaskの概要

  • 軽量でシンプル:必要最低限の機能を持ち、自分で拡張可能
  • PythonでWebアプリやAPIを手軽に作成可能
  • 開発用サーバーを内蔵しており、即座に動作確認可能

構築目的

  • Webブラウザからのリクエストに応答するWebアプリケーションやAPIを提供
  • NginxなどWebサーバーと組み合わせて、本番環境で安全・高速に運用
  • 今回はFlaskアプリ→Nginx経由でアクセス可能にするために使用

1-1. Flaskアプリの用意

mkdir -p ~/flask-app
cd ~/flask-app

app.py を作成:

from flask import Flask, send_file, abort

app = Flask(__name__)

@app.route('/api/')
def index():
    return send_file('/usr/share/nginx/html/index.html')

@app.route('/api/error-404')
def trigger_404():
    abort(404)

@app.route('/api/error-500')
def trigger_500():
    abort(500)

@app.errorhandler(404)
def handle_404(e):
    return send_file('/usr/share/nginx/html/404.html'), 404

@app.errorhandler(500)
def handle_500(e):
    return send_file('/usr/share/nginx/html/50x.html'), 500

if __name__ == '__main__':
    app.run(host='127.0.0.1', port=5000)

1-2. Flaskアプリの起動

python3 app.py

⚠️ 注意: 開発用サーバーのため本番環境には適さない。高速かつセキュアな本番用WSGIサーバの利用を推奨。


🧾 ステップ2:Nginxでリバースプロキシ設定

2-1. 設定ファイルの作成

sudo vi /etc/nginx/conf.d/default.conf

以下を追記:

# Flaskアプリ用のリバースプロキシ
location /api/ {
    proxy_pass http://127.0.0.1:5000/api/;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
}

2-2. 設定反映

sudo nginx -t && sudo systemctl reload nginx

2-3. SELinuxでの接続許可(必要な場合)

  • PolicyFile作成
sudo vi ~/nginx_local.te
module nginx_local 1.0;

require {
    type httpd_t;
    class tcp_socket name_connect;
    type http_port_t;
}

# httpd_t (nginx) が http_port_t (port 5000) に接続を許可
allow httpd_t http_port_t:tcp_socket name_connect;
  • コンパイル・適用
checkmodule -M -m -o nginx_local.mod nginx_local.te
semodule_package -o nginx_local.pp -m nginx_local.mod
sudo semodule -i nginx_local.pp
  • 動作確認(Flask直接アクセス)
curl http://127.0.0.1:5000/api/

=> index.html の内容が表示されればOK


🌐 ステップ3:ブラウザで動作確認

  • index.html の確認:
http://<サーバーのIPアドレス>/api/
  • 404エラーの確認:
http://<サーバーのIPアドレス>/api/error-404
  • 50xエラーの確認:
http://<サーバーのIPアドレス>/api/error-500

🧠 学べることまとめ

項目 内容
proxy_pass バックエンドURLにリクエストを転送
proxy_set_header クライアント情報をバックエンドに渡すヘッダー設定
URIルーティング /api/ などのパスごとの振り分け
ロードバランシング(次回) 複数アプリへの分散(次の記事で紹介予定)

🧼 トラブルシューティング

症状 原因と対策
502 Bad Gateway Flaskが起動していない、またはポートが異なる
Nginx設定エラー nginx -t で詳細確認
アクセスできない Firewalldでポートを開放 (sudo firewall-cmd --add-port=80/tcp --permanent && sudo firewall-cmd --reload)

関連記事

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?