skip to content
barorin&?

docker-composeでfastapi+PostgreSQL+pgAdminの環境を作ってみる

/ 2 min read

はじめに

docker-composeでfastapi+PostgreSQL+pgAdminの環境を作ってみようと思います。

内容

フォルダ構成

fastapi-dev
├── docker-compose.yml
└── fastapi
├── app
 ├── database.py
 ├── main.py
 └── models.py
├── Dockerfile
└── requirements.txt
# docker-compose.yml
version: '3.7'
services:
  fastapi:
    build:
      context: ./fastapi
    volumes:
      - ./fastapi/app/:/app/
    container_name: fastapi
    command: uvicorn main:app --reload --workers 1 --host 0.0.0.0 --port 8000
    ports:
      - 8000:8000
    environment:
      - DATABASE\_URI=postgresql://postgres:postgres@db/postgres_db
    depends_on:
      - postgres
    restart: always

  postgres:
    image: postgres:alpine
    volumes:
      - postgres_data:/var/lib/postgresql/data/
    container_name: postgres
    ports:
      - 5432:5432
    environment:
      - POSTGRES\_USER=postgres
      - POSTGRES\_PASSWORD=postgres
      - POSTGRES\_DB=postgres_db
    hostname: postgres
    restart: always

  pgadmin4:
    image: dpage/pgadmin4:latest
    volumes:
      - pgadmin4_data:/var/lib/pgadmin
    container_name: pgadmin4
    ports:
      - 8080:80
    environment:
      PGADMIN_DEFAULT_EMAIL: pgadmin4@test.com
      PGADMIN_DEFAULT_PASSWORD: pgadmin4
    hostname: pgadmin4
    depends_on:
      - postgres
    restart: always

volumes:
  postgres_data:
  pgadmin4_data:
# Dockerfile
FROM python:alpine

WORKDIR /app

ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONBUFFERED 1

COPY ./requirements.txt /app/requirements.txt

# Install packages
RUN apk add --no-cache postgresql-libs \
    && apk add --no-cache --virtual .build-deps gcc musl-dev postgresql-dev \
    && python3 -m pip install -r /app/requirements.txt --no-cache-dir \
    && apk --purge del .build-deps

COPY . /app/
# requirements.txt
fastapi
uvicorn
databases[postgresql]
SQLAlchemy
alembic
psycopg2
# models.py
from database import Base
from sqlalchemy import String, Boolean, Integer, Column, Text, DateTime

class Item(Base):
    __tablename__ = 'items'
    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String(255), nullable=False, unique=True)
    description = Column(Text)
    date = Column(DateTime)
    on_offer = Column(Boolean, default=False)
# database.py
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

# postgresql://{user}:{password}@{host}:{port}/{database}
engine=create_engine(
    'postgresql://postgres:postgres@postgres:5432/postgres\_db', echo=True)

Base = declarative_base()

SessionLocal = sessionmaker(bind=engine)
# main.py
from fastapi import FastAPI, Depends
from sqlalchemy.orm import Session

from database import Base, engine, SessionLocal
import models

app = FastAPI()

Base.metadata.create_all(engine) # テーブル作成

def get\_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

@app.get('/items/{id}')
def all\_fetch(db: Session = Depends(get_db)):
    items = db.query(models.Item).all()
    return items

実行

# コンテナ作成
$ docker-compose up -d --build

# アクセスは、ホストのブラウザから[http://localhost:8000](http://localhost:8000)へ