FastAPI Docker error: exec "uvicorn": executable file not found in $PATH

David Y.
jump to solution

The Problem

I’m attempting to Dockerize my FastAPI application, but it crashes with the following error right after I start up the containers with docker-compose:

Cannot start service core: failed to create shim: OCI runtime create failed: container_linux.go:380: starting container process caused: exec: "uvicorn": executable file not found in $PATH: unknown

Here is the app.Dockerfile:

FROM python:3.9
ARG POSTGRES_SERVER
ENV APP_HOME=/home/app/web
RUN mkdir -p $APP_HOME
WORKDIR $APP_HOME

RUN apk update && apk add --no-cache bash
ADD requirements.txt $APP_HOME
RUN pip install -r $APP_HOME/requirements.txt

COPY src/ $APP_HOME
CMD ["uvicorn", "app.main:app", "--reload", "--host", "0.0.0.0", "--port", "8080"]

Here is the Docker Compose configuration (app.yml):

version: '3.7'
services:
  nginx:
    env_file: .env
    build:
      context: .
      dockerfile: ./compose/local/nginx.Dockerfile
    restart: always
    ports:
       - "${EX_PORT_NGINX:-8030}:80"
    volumes:
       - ./nginx/site.conf:/etc/nginx/conf.d/default.conf
  core:
    env_file: .env
    build:
      context: .
      dockerfile: ./compose/local/app.Dockerfile
      args:
        POSTGRES_SERVER: ${POSTGRES_SERVER:-}
    restart: always
    volumes:
       - ./src:/home/app/web/
    logging:
       driver: "json-file"
       options:
          max-size: "5m"
          max-file: "10"

This is the command I’m using to start the containers:

docker-compose -f app.yml up -d

What is causing this issue and how do I fix it?

The Solution

The most likely cause of this error is that Uvicorn is not being installed in the Docker container. Make sure that your application’s requirements.txt file includes the following packages necessary to run FastAPI applications:

fastapi
uvicorn

Alternatively, these packages could be installed explicitly during the creation of the container.

FROM python:3.9
ARG POSTGRES_SERVER
ENV APP_HOME=/home/app/web
RUN mkdir -p $APP_HOME
WORKDIR $APP_HOME

RUN apk update && apk add --no-cache bash
ADD requirements.txt $APP_HOME
RUN pip install -r $APP_HOME/requirements.txt
# Install FastAPI and Uvicorn
RUN pip install fastapi uvicorn

COPY src/ $APP_HOME
CMD ["uvicorn", "app.main:app", "--reload", "--host", "0.0.0.0", "--port", "8080"]

Including these packages in requirements.txt is the recommended approach, as that will enhance the application’s portability and prevent future errors of this nature.

Considered "not bad" by 4 million developers and more than 150,000 organizations worldwide, Sentry provides code-level observability to many of the world's best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.

Sentry