Dockerizing a Python FastAPI Project Using uvNovember 26, 2025

Dockerizing a Python FastAPI Project Using uv and Uvicorn is a straightforward process that can help you deploy your application efficiently. By leveraging `uv`, a modern Python project management tool, you can streamline dependency management and environment setup.

This guide shows how to create a Python FastAPI project using `uv` and then dockerize it.

Initialize a uv Project

Start by creating a new uv project:

uv init uv-fastapi-demo

This will create a new directory `uv-fastapi-demo` with a `pyproject.toml` and default project layout.

Enter the project directory:

cd uv-fastapi-demo

Create and Activate Virtual Environment

Create and activate a virtual environment using uv:

uv venv

Activate the virtual environment:

source .venv/bin/activate

Add Dependencies and Sync

Install FastAPI and Uvicorn:

uv add fastapi uvicorn

Then sync the dependencies from the lockfile:

uv sync

Project Structure

After initialization and syncing, your project should look like this:

uv-fastapi-demo/
.venv/
.gitignore
.python-version
main.py
pyproject.toml
README.md
uv.lock

Example in `main.py`:

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"message": "Hello, uv Docker!"}

Dockerfile Using uv

In your project root, create a `Dockerfile` with the following content:

# Stage 1: Builder
FROM python:3.14-slim AS builder

# Copy uv binary from Astral.sh image
COPY --from=ghcr.io/astral-sh/uv:latest /uv /uvx /bin/

WORKDIR /app

# Copy dependency files
COPY pyproject.toml uv.lock ./

# Install dependencies in isolated environment
RUN uv sync --locked --no-dev

# Stage 2: Runtime
FROM python:3.14-slim AS runtime

COPY --from=ghcr.io/astral-sh/uv:latest /uv /uvx /bin/

WORKDIR /app

# Copy all project files
COPY . .

# Install dependencies for runtime
RUN uv sync --locked --no-dev

# Expose port
EXPOSE 8000

# Run the FastAPI app using uv and uvicorn
CMD ["uv", "run", "uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]

.dockerignore

Create a `.dockerignore` file to exclude unnecessary files from the Docker build context:

__pycache__
*.pyc
*.pyo
*.pyd
.env
.git
.venv/

Build & Run Docker

Build the image:

docker build -t uv-fastapi-demo .

Run the container:

docker run -d -p 8000:8000 --name uv-fastapi-demo uv-fastapi-demo

Then open http://localhost:8000 to see your FastAPI app running.

Cleanup

To stop the container, run:

docker stop uv-fastapi-demo

Then, if you want to remove the container:

docker rm uv-fastapi-demo

If you want to remove the Docker image:

docker rmi uv-fastapi-demo

Summary

  • `uv init` for project setup
  • `uv venv` + `source .venv/bin/activate` for virtual environment
  • `uv add` + `uv sync` for installing and locking dependencies
  • Multi-stage Dockerfile keeps runtime image small
  • `uv run uvicorn ...` starts the FastAPI app inside Docker