2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

DockerでFastAPI+SQLite3+pytest環境をつくりたい

Last updated at Posted at 2023-03-15

はじめに

PythonでAPIを作成する機会があり、今後も学んでいくのにdocker環境を作っておきたかったのでこの機会にまとめてみます

ディレクトリ構成

sample-project
┣ app
┃  ┗ main.py
┣ tests
┣ docker-compose.yml
┣ Dockerfile

各ファイル

Dockerfile
FROM python:3.9-slim-buster

RUN apt-get update && apt-get install -y libsqlite3-dev

WORKDIR /app

COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt

COPY . .

CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
docker-compose.yml
services:
  web:
    build: .
    ports:
      - "8000:8000"
    volumes:
      - .:/app
requirements.txt
fastapi
uvicorn
pytest
main.py
from fastapi import FastAPI

app = FastAPI()

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

動作確認

上記の構成でファイルを作成し、イメージのビルドを行います

$ docker-compose build

続いてコンテナの起動を行います

$ docker-compose up

image.png

localhost:8000にアクセスして以下の表示を確認できればOKです

image.png

また、localhost:8000/docsにアクセスすると、APIドキュメントを確認できました

image.png

続いて以下のコマンドでコンテナに入り、pytestを実行します

$ docker exec -it fastapi-sample-web-1 sh
# pytest

image.png

おわりに

次はエンドポイントの追加やテスト環境の作成などを行っていきます

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?