LoginSignup
2
1

FastAPI x React のDockerチートシート

Last updated at Posted at 2024-04-24

ディレクトリ構成

AppName
    ├─ back
    │   └ Dockerfile
    ├─ front
    │   └ Dockerfile
    └ docker-compose.yaml

事前準備

  • requirements.txt

back の Dockerfile

FROM python:3.10.6
WORKDIR /app
COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt
COPY . .
CMD ["uvicorn", "main:app", "--reload", "--host", "0.0.0.0", "--port", "8000"]

front の Dockerfile

FROM node:14
WORKDIR /app
COPY . .
RUN npm install
RUN npm run build
CMD ["npm", "start"]

docker-compose.yaml

version: '3'
services:
  {App名}-backend:
    build:
      context: ./back
    ports:
      - "8000:8000"
    restart: always
    tty: true
    depends_on:
      - db

  {App名}-frontend:
    build:
      context: ./front
    ports:
      - "3000:3000" 

  db:
    image: postgres:15
    volumes:
      - ./app/db/postgresql/data:/var/lib/postgresql/data
      - ./app/db/postgres:/docker-entrypoint-initdb.d
    ports:
      - "5432:5432"
    environment:
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres
      - POSTGRES_INITDB_ARGS=--encoding=UTF-8 --locale=C

volumes:
  postgres_data:

Python側でのDB接続箇所

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, scoped_session


SQLALCHEMY_DATABASE_URL = "postgresql://postgres:postgres@db:5432/postgres"

if SQLALCHEMY_DATABASE_URL:
    engine = create_engine(
        SQLALCHEMY_DATABASE_URL,
        pool_pre_ping=True,
    )
    SessionLocal = scoped_session(
        sessionmaker(autocommit=False, autoflush=False, bind=engine)
    )

    Base = declarative_base()
    Base.metadata.create_all(bind=engine)

# Dependency
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

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