Dockerize - FastAPI - UV¶
Let's dockerize my yt-comment-sentiment project which is a FastAPI app managed via UV.
Official Docs¶
- FastAPI docs for Dockerization
- UV docs for Dockerization
- UV-FastAPI example docs for Dockerization
Then, Why this?¶
I also consider above docs to fulfill my requirements but this includes:
- Multistage build to reduce final image size.
- Best and Flexible practices to use
uvin Docker. - Solution of some problems which I have encountered.
Dockerfile¶
I am taking reference of my yt-comment-sentiment which I have developed and recently and
continuously improving it.
FROM python:3.11-slim AS builder
# (1)!
COPY --from=ghcr.io/astral-sh/uv:latest /uv /bin/
# Install gcc for wordcloud
# (2)!
RUN apt-get update && apt-get install -y gcc && apt-get clean
WORKDIR /app
# (3)!
ADD pyproject.toml uv.lock /app
# Install dependencies with `--extra=backend` dependencies
RUN uv sync --extra=backend --frozen --compile-bytecode --no-install-project
# (4)!
# Copy only necessary files/folders to reduce image size
COPY params.yaml /app
COPY backend /app/backend
COPY ml /app/ml
# (5)!
RUN uv sync --extra=backend --locked
# Final stage
# (6)!
FROM python:3.11-slim AS final
# (7)!
COPY --from=builder /app /app
WORKDIR /app
# Run backend using fastapi-cli
# (8)!
CMD [".venv/bin/fastapi", "run", "--host", "0.0.0.0", "--port", "8000", "backend/app.py"]
- See official docs by
uv. - I am using
wordcloudin backend and it requiregccpackage to build wheels to work in python. - Add to install dependencies of project. But there is more in docs.
- You can also use
.dockerignoreto do this. - Re-sync project, view in docs.
- Use multistage builds to reduce image size.
-
Here we import only required files from
builderstage (which is/appdirectory) because it contains.venv/directory (where all project deps were installed) and project files. -
Finally, use
fastapi-clito run you app. See FastAPI docs.
If you get any other problem please refer to official docs.