Cloud-Powered FastAPI: Leveraging Azure for Native Hosting"

Cloud-Powered FastAPI: Leveraging Azure for Native Hosting"

A Comprehensive Tutorial on deploying FastApi on Azure

In the realm of cloud engineering, the seamless deployment of applications is paramount. As cloud-native architectures continue to evolve, leveraging the right tools and services becomes crucial for achieving scalability, reliability, and performance. Cloud engineers play a pivotal role in ensuring its efficient deployment and management within cloud environments.

In this guide, we will delve into the intricacies of natively hosting FastAPI applications on the Azure cloud infrastructure—a journey that involves orchestrating various Azure services to create a robust and scalable ecosystem.

Throughout this guide, we will explore each aspect of natively hosting FastAPI on Azure cloud infrastructure, from containerization and traffic management to data storage and monitoring. By using these Azure services in conjunction with FastAPI, cloud engineers can build scalable, resilient, and performant applications that meet the demands of modern cloud-native environments.

For this deployment, we'll require the following Azure services:

  1. Azure PostgreSQL: This fully managed relational database service will handle data persistence for our FastAPI backend. It offers high availability, durability, and robust security features essential for our application.

  2. Application Gateway: Acting as a web traffic manager, the Application Gateway will serve as a reverse proxy for our FastAPI services. It will handle SSL termination, URL-based routing, and load balancing to optimize performance and enhance security.

  3. Azure Container Registry (ACR): ACR will serve as the centralized repository for storing our Docker container images. It allows us to containerize our FastAPI application and ensure consistency and portability across different Azure environments.

  4. Azure App Service: This will host our FastAPI backend. Azure App Service provides a platform for building, deploying, and scaling web applications, enabling us to run our FastAPI application in a fully managed environment with automatic scaling and built-in monitoring.

  5. Azure Monitor: This intelligent monitoring and analytics service provides comprehensive insights into the performance and health of your Azure resources, including your FastAPI application, Azure PostgreSQL database, Application Gateway, and Azure App Service. It helps you proactively identify and address issues, ensuring optimal performance and reliability.

By leveraging these Azure services together, we can create a scalable, reliable, and performant infrastructure for deploying our infrastructure in the cloud.

Step 1. Create the Postgres DB

Sign in to the Azure Portal: Go to portal.azure.com and sign in with your Azure account. in the search bar search for the azure postgres server, click on create

Fill in the details by creating a resource group, filling the inputs, and selecting a region closer to you, for the psql version make sure to use version 14 and for the purpose of this demo, set the workload type to development

for the authentication method, we can use the default postgres authentication, create a default username and password for psql

For the networking we are going to allow public access, so that we can connect to the db, create the user and db for the db and also for to enable us use alembic to manage our migrations

You can skip the remaining tabs, and use the default settings and then click on "review+create" and go ahead create our resource.

As soon as our db is ready, copy the connection string and update the "DB_HOST" name in our .env file

# .env
DB_NAME=<DB_NAME>
DB_HOST=<AZURE_DB_HOST_URL>

Then we can go ahead and run our migrations with alembic and have our db populated and ready to go

:~$ alembic revision --autogenerate -m "new schema"
:~$ alembic upgrade head

We can now create our acr and build our docker image.

Step 2. Create ACR and build and push docker image

Back in the portal search for container registry, Fill in the details with a unique name and identifier. Since we are on the basic plan we dont have much to do here. so simply click "review+create" and create an ACR to use

Once its ready, on your host machine ensure to sign in to your azure account via the cli. run the az command to login and also login to the acr

# login into azure via cli
:~$ az login

# login to acr
:~$ az acr login --name <acr_name>.azurecr.io

After successfully logging in, go ahead and build,tag and push your image

# build the image
:~$ docker build -t <name>/<repo_name>:<tag> .

# tag the image to acr
:~$ docker tag <name>/<repo_name>:<tag> <acr_name>.azurecr.io/<repo_name>:latest

# push the image to acr
:~$ docker push <acr_name>.azurecr.io/<repo_name>:latest

Once its done, you can head over to the portal and verify that it there.

Now that our container repository is we can now create our repository for our web app to pick the docker image

Step 3. Create Azure app service

Head over to the portal and search for app service and click create, create just web app

Select your resource group and give your web app a unique name, as for the type of web app we trying to deploy, select container and select the region closest to you, again for the purpose of this demo, select the free pricing tier, F1 and proceed to the next tab

on the container tab, disable sidecar and set the image source to ACR, it should automatically fill in the others details, if not specify the new created image from acr.

After 5-7mins our app service should be ready to go

copy the default domain name and open it in your browser and view it, i added "/docs" so that we can see the swagger docs

Step 3. Create Azure Application Gateway and connect it to app service

This step is quite tricky so i'll outline all the steps for an easier understand

  1. Create an Azure Application Gateway: Search for "Application Gateway" and select it,Click on "Create" and fill out the required details like subscription, resource group, region, and name for your Application Gateway. Configure the settings for the Application Gateway, including SKU, instance count, and other parameters based on your requirements. Configure networking settings such as virtual network, subnet, and public IP address settings.

move to the next tab,

  1. Frontend Configuration: When creating the Application Gateway, you'll specify the frontend configuration, You can choose between a public or private frontend IP address or both... select public as we want it to be accessible from the internet

  1. Configure Backend Pool: Navigate to the next tab,Under the "Backend pools" section, click on "Add a backend pool". Select your App Service as the backend target by specifying its DNS name or IP address. Save the backend pool configuration.

  1. Define HTTP Settings: Configure the HTTP settings for the Application Gateway to define how it communicates with the backend. Specify settings such as the protocol, port, and cookie-based affinity.

  2. Create a Listener: Navigate to the "Listeners" section of the Application Gateway settings.Add a listener" and specify the frontend IP address and port, Choose the protocol (HTTP or HTTPS) and SSL certificate settings if applicable.

  3. Configure Routing Rules: In the "Rules" section of the Application Gateway settings, click on "Add a routing rule" Define a name for the rule and select the listener created in the previous step. Specify the backend pool and HTTP settings associated with this routing rule Optionally, define URL path-based routing rules to route requests to different backend pools based on URL paths.

  1. Enable Health Probes: Configure health probes to monitor the health of your backend instances. Define the protocol, port, and other parameters for the health probes

  2. Review and Save Configuration: Review all the settings and configurations for your Application Gateway. Once you're satisfied, save the configuration to apply the changes.

At this point you can use the IP address from your app gateway, or you can give it a custom URL, It's super easy – just head over to your favorite domain provider like GoDaddy and go into your DNS settings and add a A NAME record. This will point your domain to the IP Address of your Azure Application Gateway.

With that, we've successfully deployed our FastAPI application natively on Azure, and it's ready to conquer the digital landscape!

By harnessing the power of Azure PostgreSQL, Application Gateway, Azure Container Registry, Azure App Service, and Azure Monitor, we've built a robust and scalable infrastructure for our FastAPI backend. From data storage to traffic management and containerization, Azure has provided us with the tools to ensure our application performs optimally and remains secure.

🚧🚧🚧Don't forget to delete all your resources when you are done!🚧🚧🚧