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?

DockerとFastAPIでHello Worldした

Posted at

実行環境

  • Visual Studio Code: 1.87.0
  • OS: MacOS Sonoma 14.2.1

学習者が記録用に書いた記事です。
ご指摘、追加情報などあれば些細なことでもコメントからいただけると励みになります。

ファイルの構成

$ tree .
.
├── app
│   └── main.py
├── Dockerfile
├── docker-compose.yml
└── requirements.txt

Dockerfile

FROM python:3.11-slim-bullseye
EXPOSE 8000
WORKDIR /app
RUN apt update -y && apt-get update -y
RUN pip install --upgrade pip
COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt
COPY app .
CMD ["uvicorn", "main:app", "--host=0.0.0.0", "--reload"]
  • 別パターン(alpineを使用した場合)
FROM python:3.11-alpine3.19
EXPOSE 8000
WORKDIR /app

RUN apk update
RUN pip install --upgrade pip
COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt
COPY app .
CMD ["uvicorn", "main:app", "--host=0.0.0.0", "--reload"]

Docker Composeの設定(docker-compose.yml)

version: '3'
services:
  sample:
    build:
      context: .
    ports:
      - 8000:8000

FastAPIアプリケーション(app/main.py)

from typing import Union
from fastapi import FastAPI

app = FastAPI()

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

依存パッケージのインストール(requirements.txt)

fastapi==0.110.0
uvicorn[standard]==0.27.1

実行

以下のコマンドを使用してDockerコンテナをビルドし、起動します。

docker-compose up --build

実行結果

  • clientからGETリクエスト(curlを使用)
curl http://127.0.0.1:8000/
>> {"Hello":"World"}

8000番ポートにアクセスし、Hello Worldを得た。

参考文献

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?