使用 Docker 容器化 FastAPI 專案

實作

新增 Dockerfile 檔。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
FROM python:3.12-slim

WORKDIR /app

RUN pip install --no-cache-dir poetry

COPY pyproject.toml poetry.lock ./

RUN poetry install --no-root

COPY . .

CMD ["poetry", "run", "uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"]

EXPOSE 80

新增 docker-compose.yml 檔。

1
2
3
4
5
6
7
8
9
10
11
version: '3.8'

services:
app:
build:
context: .
dockerfile: Dockerfile
ports:
- "80:80"
environment:
- PYTHONUNBUFFERED=1

啟動服務。

1
docker compose up -d