LoginSignup
1
0

FastAPI + nginxの本番環境を作成する(オープンデータ活用②)

Last updated at Posted at 2024-03-25

※この記事はドラフト版です。

手順

  1. 本番サーバの準備
  2. nginxのインストールと起動
  3. FastAPIのインストールと起動

本番サーバの準備

さくらインターネットのVPSというサービスを契約

  • OS:Ubuntu
  • プラン:1Gプラン

nginx のインストールと起動

さくらの公式が手順を公開している
ポイントは下記

  • OSのファイアーウォール
  • さくらのVPSのパケットフィルター

FastAPIのインストールと起動

本番サーバ上で次の作業を行います。

作業ディレクトリの作成

伊万里市のオープンデータを返すAPIを作成する体で作る

mkdir fastapi
cd fastapi/
mkdir imari_city_opendata
cd imari_city_opendata/

インストール

sudo apt install python3-pip
sudo apt install python3.10-venv
python3 -m venv venv
source venv/bin/activate
pip install fastapi uvicorn[standard] gunicorn

FastAPIのコード

main.py
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"Hello": "World"}

起動確認

uvicorn main:app --reload

http://127.0.0.1:8000にアクセスしてjsonが返ってくれば成功

gunicornの準備(アプリと同じとこに準備)

nano gunicorn_conf.py
gunicorn_conf.py
from multiprocessing import cpu_count

chdir = '/home/ubuntu/app/fastapi/imari_city_opendata'

# Socket Path
bind = 'localhost:8000'

# Worker Options
workers = cpu_count() + 1
worker_class = 'uvicorn.workers.UvicornWorker'

# Logging Options
loglevel = 'debug'
accesslog = '/home/ubuntu/app/fastapi/imari_city_opendata/fastapi_access_log'
errorlog = '/home/ubuntu/app/fastapi/imari_city_opendata/fastapi_error_log'

daemon

sudo nano /etc/systemd/system/fastapi_imari_gunicorn.service
fastapi_imari_gunicorn.service
[Unit]
Description=Gunicorn Daemon for FastAPI Test Application
After=network.target

[Service]
User=ubuntu
Group=www-data
WorkingDirectory=/home/ubuntu/app/fastapi/imari_city_opendata/
ExecStart=/home/ubuntu/app/fastapi/imari_city_opendata/venv/bin/gunicorn -c /home/ubuntu/app/fastapi/imari_city_opendata/gunicorn_conf.py main:app 
[Install]
WantedBy=multi-user.target

起動

$ sudo systemctl start fastapi_imari_gunicorn
$ sudo systemctl status fastapi_imari_gunicorn

自動起動

$ sudo systemctl enable fastapi_imari_gunicorn

Nginxの設定

 sudo nano /etc/nginx/conf.d/fastapi_imari_opendata.conf
server {
        server_name example.sakura.ne.jp;

        root /home/ubuntu/app/fastapi/imari_city_opendata;

        location / {
                proxy_pass http://localhost:8000;
        }

Nginxの再起動

sudo nginx -s reload

確認

インターネット上で見ることができた
image.png

今後の予定

本番環境を用意することを最優先し、予定を組む
優先度順に並べると、次の通り

必須

  • 本番環境へのCDを試す
  • 本番環境にDBを作成
  • テストコードを作成
  • SSLを設定

その内でよい

  • コンテナで本番デプロイ
  • .sock周りを調査
1
0
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
1
0