Deploying FastAPI with Uvicorn on DigitalOcean

If you’re currently in the process of deploying your FastAPI project on DigitalOcean using Uvicorn and encountering issues with proper execution, you’ve come to the right place. In this blog post, I will walk you through the steps to overcome common challenges and ensure a smooth deployment.

One common issue when deploying FastAPI with Uvicorn is that while FastAPI runs, it may not open the desired ports on DigitalOcean’s App Platform. To address this problem, you need to modify the execution command for your app on DigitalOcean’s App Platform. Use the following code snippet to specify the command:

uvicorn main:app --host=0.0.0.0 --port=${PORT:-8000}

Explanation:

  • uvicorn main:app: This part of the command tells Uvicorn to run the FastAPI app defined in the main module.
  • –host=0.0.0.0: Setting the host to 0.0.0.0 ensures that the app is accessible from any network interface, allowing external connections.
  • –port=${PORT:-8000}: This part dynamically sets the port to the value specified by the PORT environment variable or defaults to 8000 if the variable is not set. It’s crucial for compatibility with DigitalOcean’s App Platform, as it dynamically assigns a port to your app.
    By incorporating this modified command into your app deployment process, you ensure that FastAPI correctly opens the required ports on DigitalOcean, resolving the deployment issues you might have encountered.