Deploy FastAPI and uvicorn on Azure app service

Viewed 5121

I want to deploy a simple FastAPI/uvicorn onto an Azure app service.

Everytime I deploy everything seems to work smoothly, but the moment I type in the URL for my webapp, I get following error message:

"Error" message

On my local machine, uvicorn works fine. On my webservice i run python 3.7 & fastapi 0.62.0.

Everytime I deploy, I start a document called startup.sh with only one line of code:

python -m uvicorn main:app --host 0.0.0.0 --port 80

Help is much appreciated!

2 Answers

After deployed webapp, I add some modules and add start command on portal. It works for me. (Download sample code)

1. Commands like below:

You also can add fastapi,uvicorn,uvloop,httptools in requirements.txt,let the program automatically install these modules when it is deployed.

root@3a***a3:/home/site/wwwroot# pip install fastapi
root@3a***a3:/home/site/wwwroot# pip install uvicorn
root@3a***a3:/home/site/wwwroot# pip install uvloop
root@3a***a3:/home/site/wwwroot# pip install httptools

2. Settings-> Configuration->General settings-> Startup Command.

gunicorn -w 4 -k uvicorn.workers.UvicornWorker main:app

enter image description here

Result:

enter image description here

Azure App Service for Linux with its Oryx build runner when identifies Python web apps run them using Gunicorn, a WSGI server. So your startup script can have gunicorn command to spin up the FastAPI app with the help of Gunicorn's worker class uvicorn.workers.UvicornWorker.

gunicorn -w 2 -k uvicorn.workers.UvicornWorker main:app

The -w indicates the number of workers you want to spin up with Gunicorn as master.

Alternatively, you can make the number of workers to automatically be calculated using a configuration file provided as an argument to the gunicorn as shown below.

gunicorn --config gunicorn.py main:app

And the gunicorn.py can have logic that calculates the number of worker processes and other configuration arguments for gunicorn as shown below.

import multiprocessing
import os

name = "Gunicorn config for FastAPI"

accesslog = "/home/user/fastapi/gunicorn-access.log"
errorlog = "/home/user/fastapi/gunicorn-error.log"

bind = "0.0.0.0:8000"

worker_class = "uvicorn.workers.UvicornWorker"
workers = multiprocessing.cpu_count () * 2 + 1

Also there is a detailed step by step tutorial that demonstrates How to Deploy FastAPI on Azure App Service in just 30 minutes

Related