Deploying FAST API to Digital Ocean Apps
Instructions as of January 2024.
I wanted to Deploy a quick FastAPI to Digital Ocean’s App platform in a Vercel style quick deploy but all the tutorials and Github issues did not seem to work for me but here is what did work. Others are having this issue too and its mostly due to configuration or folder structure. This will minimally work with you not having to change anything on DigitalOcean itself.
Code: https://github.com/ashayas/digital-ocean-fast-api
For the purposes of this tutorial, I will be using Gunicorn with Uvicorn Workers. I will go through each file required.
#These are the minimal files needed
main.py
app.py
Procfile
requirements.txt
__init__.py
main.py
import os
import uvicorn
from app import app
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8080)
When the script is executed, it starts the Uvicorn server with the specified application (app
) from the app
module. The server listens on the host 0.0.0.0
(making it accessible from any IP address that can reach the host machine) and uses a defined port. Essentially, this sets up and starts a web server for the provided web application. You can import the PORT from the os environment but you can also hardcode this to 8080 and it should work.
app.py
This is just the simplest FastAPI file [1]
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
Procfile
web: gunicorn -w 2 -k uvicorn.workers.UvicornWorker --bind 0.0.0.0:8080 --worker-tmp-dir /dev/shm app:app
There is a lot going on here. You can also have a gunicorn_config.py and have your Procfile point to it which would yield better organization but in my experience we don’t really change too much in this file so having one file just makes it cleaner.
web:
: This declares a web process type and tells the platform (like Digital Ocean) that this command should be used to start your web server.gunicorn
: This is the command to start the Gunicorn server.-w 4
: Sets the number of worker processes to 4. You can also use 2 for most bare usecases or even 1.-k uvicorn.workers.UvicornWorker
: Specifies the worker class to be Uvicorn workers, suitable for ASGI applications.--bind 0.0.0.0:8080
: Tells Gunicorn to bind to all public IPs at port 8080.--worker-tmp-dir /dev/shm
: Sets the temporary directory for workers to/dev/shm
.app:app
: Indicates the Python module (app
) and the application object (app
) to run.
requirements.txt
Simple just your requirements for the app. Minimally I used, including versions these ones:
fastapi>=0.108.0
uvicorn>=0.25.0
gunicorn>=20.1.0
Pushing this to Git and then letting Digital Ocean run through next steps should work and adjust based on traffic. Happy deployment! 🚀