Breno Ingwersen
Breno Ingwersen

Reputation: 21

How to run a FastAPI application on a multi-stage build using pdm as dependency manager?

I'm trying to run a FastAPI application using pdm and the following Dockerfile:

ARG PYTHON_BASE=3.10-slim

# Build stage
FROM python:$PYTHON_BASE as build

COPY pyproject.toml pdm.lock README.md ./

# Install pdm
RUN python -m pip install --upgrade pip setuptools wheel &&\
    pip install pdm

# Install dependencies
RUN pdm install --no-lock --no-editable


# Run stage
FROM python:$PYTHON_BASE

# Copy application files
COPY src /src
COPY logging_config.yaml .

COPY --from=build /.venv /.venv
ENV PATH="/.venv/bin:{$PATH}"

EXPOSE 5000

CMD ["uvicorn", "src.backend.main:app", "--host", "0.0.0.0", "--port", "5000"]

My project structure is the following:

backend
|- src/backend
|  |- main.py
|- Dockerfile
|- pdm.lock
|- pyproject.toml
|- README.md

I'm receiving the following error after the following commands are run to build the image and run the container:

sudo docker build -t backend:v0.1.0 .
sudo docker run -p 5000:5000 backend:v0.1.0

The error: exec /.venv/bin/uvicorn: no such file or directory

Can anyone explain how to set up the container properly?

At first I thought the container wasn't able to find a PATH to the virtual environment to uvicorn, so I accessed the container's bash which resulted in:

docker run -it backend:v0.1.0 /bin/bash
which uvicorn
>>> /.venv/bin/uvicorn

Upvotes: 0

Views: 170

Answers (1)

Breno Ingwersen
Breno Ingwersen

Reputation: 21

I was able to identify the problem. It seems I initialized the pdm project with Python 3.12 while trying to deploy the application using Python 3.10. This mismatch resulted in the container looking for a 3.10 venv while a 3.12 was being created. So I just updated the base image to python:3.12-slim and the Dockerfile worked as it is.

Upvotes: 1

Related Questions