Search code examples
fastapigoogle-cloud-runuvicorn

Cloud Run deployment failing for FastAPI


I have a Seleniumbase (manager module) app I want to deploy to Cloud Run. In my server.py file I have my FastAPI app.

server.py

from fastapi import FastAPI, Response
from pydantic import BaseModel
from manager import start
from database import Client
import uvicorn
import os

app = FastAPI()

class Job(BaseModel):
    customer_id: str

@app.get("/", tags=["healthCheck"])
def health(response: Response):
    return {"status": "OK"}

@app.post("/job")
def run_job(data: Job, response: Response):
    try:
        client = Client()
        config = client.get_config(data.customer_id)
        start(
            config.tasks,
            config.destinations,
            use_proxies=True,
            customer_id=data.customer_id
        )

        return {"success": True}

    except Exception as e:
        response.status_code = 500
        return {"success": False}
    

if __name__ == "__main__":
    uvicorn.run(app, host='0.0.0.0', port=8080)

Dockerfile

FROM ubuntu:22.04

ENV DEBIAN_FRONTEND noninteractive
RUN apt-get update -y && apt-get install -y wget xvfb python3-pip python3 python3-dev default-libmysqlclient-dev build-essential
RUN apt-get install -y libxss1 libappindicator1 libgconf-2-4 \
    fonts-liberation libasound2 libnspr4 libnss3 libx11-xcb1 libxtst6 lsb-release xdg-utils \
    libgbm1 libatk-bridge2.0-0 libgtk-3-0 libxcb-dri3-0

RUN apt-get install -y wget
RUN wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - \ 
    && echo "deb http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list
RUN apt-get update && apt-get -y install google-chrome-stable

RUN set -e
RUN echo "Starting X virtual framebuffer (Xvfb) in background..."
RUN Xvfb -ac :99 -screen 0 1920x1080x16 > /dev/null 2>&1 &
RUN export DISPLAY=:99
RUN exec "$@"

WORKDIR /app

COPY . /app

RUN pip3 install -r ./requirements.txt
RUN seleniumbase get chromedriver --path

EXPOSE 8080

CMD ["python3", "server.py"]

When deploying this to Cloud Run I'm getting the following error

Revision 'tag-00008-vwn' is not ready and cannot serve traffic. The user-provided container failed to start and listen on the port defined provided by the PORT=8080 environment variable. Logs for this revision might contain more information.

Building the image and running the container locally works as expected. I've already tried to:

  • Run uvicorn like so uvicorn.run("server:app", <kwargs>)
  • Run the app using fastapi-cli CMD ["fastapi", "run", "server.py", "--port", "8080"] in Docker (without uvicorn)
    • Change server.py to app/server.py

EDIT Altough @NoCommandLine's solution does work to host the server I ended up having problems with python-dotenv not loading the .env file properly inside the docker container on Cloud Run. This was not apparent from the log explorer.


Solution

  • Try one of these

    Option A

    1. Remove EXPOSE 8080 from your Docker file

    2. Change the last line in your Docker file to

      CMD exec python3 server.py

    Option B

    1. Update your Docker file to

          ENV PORT 8080
      
          CMD exec uvicorn server:app --host 0.0.0.0 --port ${PORT}
      
    2. Then update server.py and delete

         if __name__ == "__main__":
           uvicorn.run(app, host='0.0.0.0', port=8080)