LoginSignup
2
0

簡単にNginxでfastapiをデプロイする

Last updated at Posted at 2024-01-01

はじめに

今までapacheやtomcatでデプロイすることがほとんどだったが、最近のgoやpythonのフレームワークはNginxでデプロイする方法で書かれていることが多いので、気になって調べてみた。
ついでに最近はまっているfastapiをデプロイするためのフレームワークとした。
Nginxでfastapiを自分でパソコンでデプロイする方法を書いておく。

Version

windows 11
python: 3.9.13

requirements.txt
fastapi==0.105.0
uvicorn==0.25.0

fastapi

fastapiをインストール

  • python はインストールされていることが前提
cmd
pip install fastapi
pip install uvicorn

fastpai用のファイルを作成する

main.py
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def mainpage():
    return "hello!"

fastapiを実行する。

cmd
# デプロイ用
uvicorn main:app --host 127.0.0.1 --port 8000

# 開発用(リロードあり)
uvicorn main:app --host 127.0.0.1 --port 8000 --reload

Nginx

Nginxのインストール

  • Stable Version の nginx/Windows-1.24.0 をインストール。
  • 圧縮解凍しC:/にフォルダをおいた。
cmd
# Nginxフォルダに移動
cd C:\nginx-1.24.0

# 実行
start nginx

# 再スタート (設定ファイル編集後)
nginx -s reload

# 停止
nginx -s stop

Nginxの起動確認

  • localhost:80

image.png

Nginxのnginx.confファイルを編集する

  • C:/nginx-1.24.0/conf/nginx.conf
nginx.conf
    server {
        # 80 -> 81 に変更
        listen 81;
		listen [::]:81;
		server_name localhost;

		root /var/www/プロジェクト;
		index index.html;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        # location / {
        #     root   html;
        #     index  index.html index.htm;
        # }

        #追加した部分
        location / {
			proxy_pass http://localhost:8000;
			proxy_set_header Host $http_host;
			proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
			proxy_set_header X-Forwarded-Proto $scheme;
			proxy_redirect off;
        }
  • listenでportを指定し、location/ {...} を追加した。
  • Nginxを再起動
  • 外からport81に接続したとき、proxyでlocalで実行中のport8000と通信するようにした。

image.png

  • port81から接続して問題なくport8000で起動しているfastapiが動作していることが見える。
  • ここでスマホからWifiを切りwww.自分のドメイン:81 or IPアドレス:81に接続すれば動作を確認できる。

おわりに

今までapacheやtomcatでサーバーを作ってきたので、Nginxを触ったのは初めてだった。少しのネット情報からコピペで簡単にデプロイできたので、かなり軽い印象は受ける。
今後はNginxでgolangのフレームワークなどがデプロイできるようにしたい。

2
0
1

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
0