Azure

Deploy Python FastAPI using Azure Container Registry

Introduction

In the world of software development, containerization has become a game-changer. It allows developers to create, deliver, and run applications seamlessly across different environments. One powerful platform that simplifies container management is Azure Container Registry (ACR), offered by Microsoft Azure. It has gained popularity among developers for its robustness and scalability. In this article, we will explore the possibilities of deploying a Python FastAPI application using Azure Container Registry. FastAPI is known for its speed, simplicity, and flexibility, making it a favorite among developers. By combining the strengths of FastAPI and Azure Container Registry, we can ensure reliable and scalable development and deployment. So, let’s dive into the exciting world of containerized web apps with FastAPI and Azure Container Registry!

What is FastAPI?

FastAPI is a modern and high-performance web framework used for building APIs with Python. It offers simplicity, efficiency, and ease of use, making it a popular choice for developers who want to create robust and fast web applications. One of FastAPI’s notable features is its ability to automatically generate detailed and interactive API documentation using Python-type hints. This feature not only helps developers understand the available endpoints but also allows them to interact with the API directly through user-friendly interfaces like Swagger UI or ReDoc.

How does FastAPI work?

Here’s a simplified explanation:

  • Easy to Use: FastAPI provides a user-friendly approach to defining and handling API endpoints.
  • Fast and Efficient: FastAPI utilizes asynchronous programming, enabling it to handle multiple requests simultaneously, resulting in impressive speed and efficiency.
  • Automatic Documentation: With FastAPI, your API documentation is generated automatically based on the code you write. This saves you time and effort in maintaining separate documentation.
  • Data Validation: FastAPI ensures that the data sent to your API is valid and correct, enhancing the reliability of your application.
  • URL Routing: FastAPI helps organize your API endpoints using URLs, simplifying the management and maintenance of your web application.
  • Request Handling: FastAPI automatically parses request data (e.g., JSON payloads or form data) and provides easy access within the view function. It also handles serialization of 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’s pip:

pip install fastapi
pip install "uvicorn[standard]"

Step 2: Create a file named main.py with the following code:

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

from fastapi import FastAPI

app = FastAPI()

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

This code sets up a simple GET endpoint for demonstration purposes.

Step 3: Run the program:

python -m uvicorn main:app --reload

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

You can also specify a different port of your choice using the command:

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

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

Setup the Azure Container Registry

Azure Container Registry acts as a centralized repository for containerized applications. It stores and manages these containers, ensuring easy access, sharing, and downloading. Think of it as a library where you can borrow program containers. By leveraging Azure Container Registry, developers and teams can efficiently manage and distribute their software.

Step 1: On the Azure portal, search for Azure Container Registry.

Step 2: Select Azure Container Registry from the results.

Step 3: Click on Create.

Step 4: Select the subscription type and create a new Resource Group. Provide a meaningful name for your Registry. Click on Review + Create and verify all the details. Finally, click Create to create your Container Registry.

Step 5: Wait for a minute until your Container Registry is created. Once you see the “deployment is complete” message, your Container is ready. Click on the Go to Resource button.

Step 6: You will now see the Container Registry Dashboard. To push your FastAPI code into this container, you will need an access key. Click on Access Keys in the left navigation bar.

Step 7: In the Access Keys section, you will find your Registry name, Login server, and Admin user information. By default, the Admin User is disabled. Enable it to see your Username and two Passwords: Password1 and Password2. Make a note of these credentials. They will be used to push your FastAPI code into the container.

Create Container Image using Docker Build

Before creating an image, make sure to freeze your Python modules in a requirement.txt file.

Step 1: Create a Dockerfile:

Step 2: Configure the Dockerfile with the necessary details, such as the Python version, directory copying, 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 and paste this code into your Dockerfile.

Step 3: Log in to your Azure Container registry using the WSL terminal and the login command provided:

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

Note: Replace [Your Azure Login server URL], [Username], and [Password] with your container credentials. Ensure that your Docker runs in the background.

Step 4: Build your container image using the following command:

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

Note: Replace [Azure Login server], [Container name], and [Tag] with your container credentials. The Tag helps version your container image.

Step 5: Test your image before pushing it to the main server using the following command:

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

Note: Replace [Azure Login server], [Container name], and [Tag] with your container credentials.

By running this command, your image will be accessible on http://localhost:8040/docs. Test all your endpoints, and if everything works fine, you can proceed to push the image to your Azure Container Registry.

Step 6: Push the image to Azure Container Registry using the following command:

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

Note: Replace [Azure Login server], [Container name], and [Tag] with your container credentials.

Step 7: Check the image in your Azure Container Registry by clicking on Repositories in the left navigation bar. You will see your image listed in the Repositories section.

Create an App Service for Deployment

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

Step 1: Search for App Service on the Azure portal and select App Service. Click on the Create icon and choose Web App.

Step 2: Create a Web App. Select the subscription and Resource Group, provide a meaningful URL, select Docker Container, and choose Linux as the operating system. Click Next: Docker.

Step 3: Set up Docker. Select Single Container as the option, choose Azure Container Registry as the Image Source, and select the Registry you created earlier. The image name and tag will be automatically detected. Click on Review + Create, verify all the details, and then click Create.

Step 4: Wait for a minute for your container to deploy. Once you see the deployment complete screen, click on the Go to Resource button.

Step 5: The deployment is complete, and you will see the URL where your FastAPI application is hosted.

Congratulations! You have successfully hosted your FastAPI application in Azure using Azure Container Registry.

Conclusion

Deploying Python FastAPI using Azure Container Registry simplifies and accelerates the process of launching web applications on the internet. It’s like packaging your app in a box and storing it in a secure place called Azure Container Registry, ensuring easy management and sharing of your applications. By leveraging Azure Container Registry, you can ensure that your apps run smoothly in different environments and can scale efficiently to handle increased traffic.

At Skrots, we also offer similar services to our clients. We provide seamless deployment of Python FastAPI applications using our own container registry solution. Just like Azure Container Registry, our platform ensures reliability, scalability, and easy management of containerized applications. If you want to experience the power of containerized web apps with FastAPI, we recommend visiting Skrots to explore our services. Feel free to check out all the services we provide at https://skrots.com/services. Thank you for choosing Skrots!

FAQs

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

A: Azure Container Registry is a secure and private container registry service provided by Microsoft Azure. You should use it to deploy your FastAPI application because it simplifies container management, storage, and distribution, ensuring a reliable and scalable deployment process.

Q: How does containerization benefit my FastAPI application deployment?

A: Containerization packages your FastAPI application and its dependencies into a single container, ensuring consistency and easy portability. It eliminates the challenges caused by differences in environments, making deployment smoother and more reliable.

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

A: Absolutely! Azure Container Registry seamlessly integrates with other Azure services, enabling features like continuous integration and continuous deployment (CI/CD), auto-scaling, and monitoring. 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 simplifies scaling by allowing the distribution and deployment of multiple instances of your containerized app across various servers. This ensures effective handling of increased traffic and user demand.

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

A: Absolutely! 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 eliminates the need for manual intervention and ensures your app stays up-to-date effortlessly.

At Skrots, we also offer similar services to our clients. We provide seamless deployment of Python FastAPI applications using our own container registry solution. Just like Azure Container Registry, our platform ensures reliability, scalability, and easy management of containerized applications. If you want to experience the power of containerized web apps with FastAPI, we recommend visiting [Skrots](https://skrots.com) to explore our services. Feel free to check out all the services we provide at [https://skrots.com/services](https://skrots.com/services). Thank you for choosing Skrots!

Show More

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button