Deploy Python FastAPI using Azure Container registry

Introduction

Containerization is a revolutionary technology in software development, allowing developers to create, deliver, and run applications smoothly in different environments. Azure Container Registry (ACR) is a strong and dependable platform offered by Microsoft Azure to manage container images at scale. It simplifies the process of storing and deploying containers, making it a popular choice among developers. This article is all about containerized web applications and how to deploy a Python FastAPI application using Azure Container Registry. FastAPI is a web framework known for being fast, simple, and flexible, making it very popular among developers. When we combine the strengths of FastAPI with Azure Container Registry, we can make development and deployment much smoother and ensure that our applications are reliable and can grow as needed. So, let's dive in and explore this exciting world of containerized web apps with FastAPI and Azure Container Registry!

What is FastAPI?

FastAPI is a modern and high-performance web framework for building APIs with Python. It is designed to be simple, efficient, and easy to use, making it a popular choice for developers who want to create robust and fast web applications.FastAPI leverages Python-type hints to automatically generate detailed and interactive API documentation. This feature is incredibly useful as it not only helps developers understand the available endpoints but also allows them to interact with the API directly through a web-based interface like Swagger UI or ReDoc.

How does FastAPI work?

Here's how it works in simple terms:

  • Easy to Use: FastAPI is designed to be simple and user-friendly. It provides a straightforward way to define and handle API endpoints.
  • Fast and Efficient: It is super speedy! FastAPI uses a technique called asynchronous programming, which allows it to handle multiple requests at the same time, making it very fast and efficient.
  • Automatic Documentation: FastAPI can automatically create documentation for your API based on the code you write. This means you don't have to spend extra time writing documentation separately.
  • Data Validation: It helps ensure that the data sent to your API is valid and correct. This way, you can avoid errors and make your application more reliable.
  • URL Routing: FastAPI helps organize your API endpoints using URLs, making it easy to manage and maintain your web application.
  • Request Handling: When a request comes in, FastAPI automatically parses the request data, such as JSON payloads or form data, and provides easy access to it within the view function. Similarly, it also takes care of serializing the response data into the appropriate format.

Prerequisites

  • Python 3.7+ 
  • Docker 4.10+
  • Ubuntu 22.04.2 LTS

Installation

Step 1. Install FastAPI and Uvicorn using Python pip

pip install fastapi
pip install "uvicorn[standard]"

Step 2: Create main.py file with :

########## main.py ##########

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"Hello": "World"}

I have created a simple GET endpoint for better understanding.

Step 3. Run the program 

python -m uvicorn main:app --reload

After executing this command, you will see that your program will be running on an 8000 port :

You can also change the port of your choice using this command.

python -m uvicorn main:app --reload --port 8040

After running this command, now you can access the Swagger using http://127.0.0.1:8040/docs.

Setup the Azure Container Registry

A container registry is like a big library or storage place for computer programs, specifically containerized applications. Containers are like small, self-contained packages with all the software and settings for an application to run smoothly. They are used to ensure that an application works consistently across different environments. The container registry keeps all these containerized applications in one place, so people can easily access, share, and download them when needed. It's similar to how you might go to a library to borrow a book. The registry stores these containers, making it convenient for developers and teams to manage and distribute their software efficiently.

Step 1. Click on the search button and search Container Registry on the Azure portal.

Step 2. Select Container Registry shown below.

Step 3. Now click on Create.

Step 4. Now select the subscription type, and create the new Resource Group. If you have your own, then use that and give a meaningful Registry name, then click on Review + Create Button. then verify all the stuff and click on Create Button to create your Container Registry.

Step 5. After that, wait for a minute to create your Container Registry. When you see a deployment is a complete message, it means your Container is ready. Click on the Go to Resource Button.

Step 6. Now you will see the Container Registry Dashboard. And you have to push your FastAPI code in this container. To push your code, you need an access key to this Container. So click on Access Keys on your left Nav bar.

Step 7. Then you will see the Registry name, the Login server, and the Admin user. And by default Admin User is Disabled, so you have to Enable that. Then you will see your Username and two Password that is Password1 and password2. Copy all those stuff. It will help you to push your FastAPI in this container.

Create Container Image using Docker Build

Note: before creating an image you first, you have to freeze your Python module in requirement.txt.

Step 1. Create a Docekr file with the name Dockerfile.

Step 2. Now configure the Dockerfile with all the stuff like their Python version, copy the directories, and the run command.

FROM python:3.10

WORKDIR /data
COPY . /data

RUN pip install -r requirement.txt

COPY . .

CMD [ "uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80" ]

Copy this and paste it into your Dockerfile.

Step 3. Then log in with your Azure Container registry using the WSL terminal, and the login command was given below.

docker login [Your Azure Login server URL] -u [Username] -p [Password] 

Note. Replace Azure Server URL, Username, and Password from your container Credential. make sure your docker runs in the background.

Step 4. Now run your Dockerfile and build the container image using the given command.

docker build -t [Azure Login server]/[Container name]:[Tag] .

Note. Replace the Azure Login server, Container name, and the Tag from your credentials. This Tag will help to give your container image version.

Step 5. Test your Image before the push on the main server. you can test your using the given command.

docker run -p 8040:80 [Azure Login Server]/[Container name ]:[tag]

Note. Replace the Azure Login server, Container name, and the Tag from your credentials.

By running this command, your image will be running on the docker on http://localhost:8040/docs, test your all endpoints, and if all working fine, then you will be ready to push on your Azure Container registry.

Step 6: Push the image on the Azure registry using the given command:

docker push [Azure Login server]/[Container name]:[tag]

Note. Replace the Azure Login server, Container name, and the Tag from your credentials.

Step 7. Check this image on the Azure Container registry. click on Repositories from your left nav bar in the Azure Container registry, and you will see your image as came into your Repositories.

Create an App Service for deployment

Azure App Service is a cloud computing platform provided by Microsoft, which allows developers to build, deploy, and manage web applications and APIs without worrying about the underlying infrastructure. In simple terms, think of Azure App Service as a virtual space where you can create and host your website or web application without needing to set up and maintain servers yourself. It takes care of the technical stuff, so you can focus on building your website or app and making it available to users on the internet.

Step 1. Click on the search option and search App Service, then select App Service. And click on Create icon, then select Web App.

Step 2. Create a Web App. Select subscription and Resource Group, then give your meaningful Url, select Docker Container, and select Operating system as Linux. Then click Next: Docker Button.

Step 3: Setup the Docker. First, select options as Single Container, select Image Source as Azure Container Registry, then select the Registry that you have created earlier, then the image name and tag will detect automatically. After completing this then, click the Review + Create Button then, verify all the stuff, and then click Create button.

Step 4.  After that, wait for a minute to deploy your container, then you will see the deployment complete screen. Now click on the Go to Resource button.

Step 5. Deployment Completed, and you will see the hosted FastAPI URL:

And here, you successfully host your FastAPI in Azure using Azure Container Registry.

Conclusion

Deploying Python FastAPI using Azure Container Registry allows developers to easily and quickly launch their web applications on the internet. It's like putting your app in a box and storing it in a special place called Azure Container Registry. This helps developers manage and share their apps with others easily. By doing this, they can ensure their apps work well even when lots of people use them at the same time. It's a smart and efficient way to make sure their apps run smoothly and are available for everyone to use!
Moreover, Azure Container Registry can work together with other Azure services, providing developers with a complete set of tools to manage their applications. This includes features like automatic deployment updates, so whenever developers make changes to their code, the updates get applied automatically to the running application without any downtime. It's like keeping the app up-to-date effortlessly.

FAQs

Q. What is Azure Container Registry, and why should I use it to deploy my FastAPI application?

A.  Azure Container Registry is a service provided by Microsoft Azure that acts as a secure and private container registry. You should use it to deploy your FastAPI application because it simplifies the process of managing, storing, and distributing containerized applications, making deployment more reliable and scalable.

Q. How does containerization benefit my FastAPI application deployment?

A.  Containerization packages your FastAPI application and all its dependencies into a single container, ensuring consistency and easy portability. It helps avoid potential issues caused by differences in environments, making deployment smoother and more reliable.

Q.  Can I use Azure Container Registry with other Azure services?

A.  Yes! Azure Container Registry seamlessly integrates with other Azure services, enabling features like continuous integration and continuous deployment (CI/CD), monitoring, and auto-scaling. This allows you to build a comprehensive application ecosystem in the Azure cloud.

Q.  How does Azure Container Registry help with scaling my FastAPI application?

A.  Azure Container Registry makes it easier to scale your FastAPI application by allowing you to distribute and deploy multiple instances of your containerized app across various servers. This helps handle increased traffic and user demand effectively.

Q.  Can I automatically update my deployed FastAPI application when I make changes to the code?

A.  Yes, Azure Container Registry can be integrated with Azure services like Azure Kubernetes Service (AKS) or Azure Web App, enabling automatic updates to your application whenever you push changes to the container registry. This helps keep your app up-to-date without manual intervention.