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

FastAPIとReact, Herokuを使用した小規模アプリのデプロイとホスティング

Posted at

最小限の機能を持つバックエンドとフロントエンドのデプロイをしてみました。

フロントエンド

初期化

npm create vite@latest <your-frontend-folder-name> --template react-ts
cd <your-frontend-folder-name>
npm install

キーとなるファイル

  • index.html: エントリーポイント
  • src/main.jsx: Reactのエントリーファイル
  • src/App.jsx: Reactの根幹となるコンポーネント

src/App.tsxの改修

以下のコードで、フロントエンドのフォルダにあるsrc/App.tsxを更新する。

import React from 'react';

function App() {
  return (
    <div>
      <h1>Hello from React + Vite!</h1>
    </div>
  );
}

export default App;

フロントエンドサーバーの動作確認

以下のコードを起動してブラウザでサーバーが立ち上がるか確認する。

npm run dev

アプリを指定されたURL(e.g., http://localhost:5173)で閲覧する。

バックエンド

セットアップ

  1. FastAPIとUvicornのインストール
  • バックエンドのために新しいフォルダを作る (e.g., backend)
  • 依存しているライブラリをインストールする
pip install fastapi uvicorn
  1. バックエンドのフォルダを作成
cd ..
mkdir <your-backend-folder-name>
  1. バックエンドのフォルダにmain.pyを作成
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"message": "Hello from FastAPI!"}
  1. バックエンドサーバー動作確認
uvicorn main:app --reload --host 0.0.0.0 --port 8000

http://127.0.0.1:8000 にアクセスして確かめる。

フロントエンドとバックエンドの繋ぎ込み

  1. CORS (Cross Origin Resource Sharing)の適用
    バックエンドのフォルダにあるmain.pyを以下のように更新する。
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # Adjust this for production
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.get("/")
def read_root():
    return {"message": "Hello from FastAPI!"}
  1. React側でのデータ取得
    フロントエンド側のフォルダにあるsrc/App.tsxを以下のように編集する。
import { useEffect, useState } from 'react';

function App() {
  const [message, setMessage] = useState("");

  useEffect(() => {
    fetch("http://127.0.0.1:8000/")
      .then((response) => response.json())
      .then((data) => setMessage(data.message));
  }, []);

  return (
    <div>
      <h1>{message}</h1>
    </div>
  );
}

export default App;

Herokuにデプロイ

フロントエンド

  1. フロントエンドのフォルダに移動し、新しいHerokuアプリを作成し、Node.jsとNGINXビルドパックを追加する
heroku create <your-frontend-app-name>
heroku buildpacks:add heroku/nodejs -a <your-frontend-app-name>
heroku buildpacks:add heroku-community/nginx -a <your-frontend-app-name>
  1. フロントエンドのフォルダのルートにconfigフォルダを追加して、nginx.conf.erbというファイルを追加する
mkdir config
touch config/nginx.conf.erb
  1. nginx.conf.erbに以下の内容を追加する
worker_processes 1;
events { worker_connections 1024; }
http {
    include mime.types;
    default_type application/octet-stream;
    sendfile on;
    keepalive_timeout 65;

    server {
        listen <%= ENV["PORT"] %>;
        root /app/dist;

        location / {
            try_files $uri /index.html;
        }
    }
}
  1. package.jsonを以下のように更新
{
  "name": "my-react-app",
  "version": "1.0.0",
  "private": true,
  "description": "A simple React.js application using Vite",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "serve": "vite preview",
    "start": "serve -s dist"
  },
  "dependencies": {
    "vite": "^4.4.5",
    "@vitejs/plugin-react": "^4.0.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0"
  },
  "devDependencies": {
    "vite": "^4.0.0",
    "@vitejs/plugin-react": "^4.0.0"
  },
  "engines": {
    "node": ">=14.x",
    "npm": ">=6.x"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}
  1. viteをインストールする

viteがpackage.jsonのdevDependenciesではなくdependenciesに入ることがポイントで、これにより本番環境でもviteが使えるようになる。

npm install vite @vitejs/plugin-react --save
  1. serveパッケージをインストールする
    Herokuはビルドしたファイルをdistフォルダからサーバーに使う必要があるため、serveパッケージをインストールする。
npm install --save serve
  1. フロントエンドのフォルダのルートにあるvite.config.jsを以下のように編集する
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
  plugins: [react()],
  build: {
    outDir: 'dist' // Output folder for production builds
  }
});
  1. フロントエンドのpublic/index.htmlを以下のように更新する
<!doctype html>
<html lang="en">
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.tsx"></script>
  </body>
</html>
  1. ルートにProcfileを置いて中身を以下のように編集する
web: npm start
  1. フロントエンドのフォルダのルートにstatic.jsonを追加して、以下のように編集する
{
    "root": "dist/"
}
  1. フロントエンド側のフォルダでアプリをビルドする。
npm run build
  1. Herokuにデプロイ
git init
heroku git:remote -a <your-frontend-app-name>
git add .
git commit -m "Deploy frontend"
git push heroku main

バックエンド

  1. Procfileをバックエンドのフォルダのルートに追加する
web: uvicorn main:app --host=0.0.0.0 --port=${PORT}
  1. 依存先ライブラリ一覧(requiremens.txt)を作成
pip freeze > requirements.txt

私の環境ではrequirements.txtは以下でした。

fastapi==0.115.12
uvicorn==0.34.0
  1. Herokuにデプロイ
heroku create <your-backend-app-name>
git init
git add .
git commit -m "Deploy backend"
git push heroku main

デプロイ後にすること

フロントエンドのsrc/App.tsxにはバックエンドのURLが載っているが、それはローカルホスト用。Herokuにデプロイした後は、実際にバックエンドのアプリを開いて実際のURLを確認し、App.tsxを修正する必要がある。変更後はフロントエンドのアプリを再度デプロイすること。

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