How to Deploy a FastAPI Application with Docker on Azure
FastAPI has gained immense popularity among developers for its simplicity and performance. When combined with Docker, you can easily create, package, and deploy your FastAPI applications in a reproducible environment. In this article, we’ll walk through the steps to deploy a FastAPI application using Docker on Azure, providing you with clear code examples, actionable insights, and troubleshooting tips along the way.
What is FastAPI?
FastAPI is a modern web framework for building APIs with Python 3.6+ based on standard Python type hints. It is designed to create high-performance applications quickly, thanks to its asynchronous capabilities and built-in data validation. FastAPI is particularly well-suited for microservices and applications requiring rapid iteration.
Use Cases for FastAPI
- Microservices Architecture: FastAPI is ideal for building small, independent services that communicate over HTTP.
- Data Science APIs: Quickly expose machine learning models as APIs.
- Web Applications: Serve as back-end services for web applications with frameworks like React or Vue.js.
- IoT Applications: Handle requests from devices efficiently.
Prerequisites
Before we start deploying our FastAPI application, ensure you have the following:
- An Azure account
- Docker installed on your machine
- Basic understanding of FastAPI and Python
- Azure CLI installed for deployment
Step 1: Create a Simple FastAPI Application
Let’s begin by creating a basic FastAPI application. Create a folder named fastapi-docker-azure
and add a file called main.py
.
# main.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/items/{item_id}")
def read_item(item_id: int):
return {"item_id": item_id}
Directory Structure
Your directory should look like this:
fastapi-docker-azure/
├── main.py
Step 2: Create a Dockerfile
Next, we need to create a Dockerfile to containerize our FastAPI application. In the same folder, create a file named Dockerfile
:
# Dockerfile
FROM tiangolo/uvicorn-gunicorn-fastapi:python3.9
# Set the working directory
WORKDIR /app
# Copy the application code
COPY ./main.py .
# Expose the port
EXPOSE 80
# Command to run the application
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"]
Step 3: Build the Docker Image
With the Dockerfile in place, you can build your Docker image. Open your terminal, navigate to the fastapi-docker-azure
directory, and run the following command:
docker build -t fastapi-azure:latest .
Step 4: Test Locally with Docker
Before deploying to Azure, let’s test our application locally. Run the Docker container with the following command:
docker run -d --name fastapi-app -p 8000:80 fastapi-azure:latest
You can access your FastAPI application by navigating to http://localhost:8000
in your browser. You should see the message {"Hello": "World"}
.
Step 5: Push Docker Image to Azure Container Registry
To deploy our application on Azure, we need to push our Docker image to Azure Container Registry (ACR).
-
Login to Azure:
bash az login
-
Create an Azure Container Registry:
bash az acr create --resource-group <YourResourceGroup> --name <YourRegistryName> --sku Basic
-
Login to ACR:
bash az acr login --name <YourRegistryName>
-
Tag your Docker image:
bash docker tag fastapi-azure:latest <YourRegistryName>.azurecr.io/fastapi-azure:latest
-
Push your Docker image to ACR:
bash docker push <YourRegistryName>.azurecr.io/fastapi-azure:latest
Step 6: Deploy the Docker Image on Azure Web App
Now that your image is in ACR, you can deploy it to Azure Web App.
-
Create an Azure Web App:
bash az webapp create --resource-group <YourResourceGroup> --plan <YourAppServicePlan> --name <YourWebAppName> --runtime "DOCKER"
-
Configure the Web App to use ACR:
bash az webapp config container set --name <YourWebAppName> --resource-group <YourResourceGroup> --docker-custom-image-name <YourRegistryName>.azurecr.io/fastapi-azure:latest --docker-registry-server-url https://<YourRegistryName>.azurecr.io
-
Start the Web App:
bash az webapp start --name <YourWebAppName> --resource-group <YourResourceGroup>
Step 7: Access Your FastAPI Application
Once your Azure Web App is running, you can access it via https://<YourWebAppName>.azurewebsites.net
. You should see the same output as when you tested it locally.
Troubleshooting Tips
-
Container Not Starting: Check the logs of your Azure Web App using:
bash az webapp log tail --name <YourWebAppName> --resource-group <YourResourceGroup>
-
Network Issues: Ensure that the correct ports are exposed and that your Azure Web App allows HTTP traffic.
-
Image Not Found: Verify that the image exists in your Azure Container Registry and that you have correctly configured the Web App to use it.
Conclusion
Deploying a FastAPI application with Docker on Azure not only enhances your application’s scalability but also streamlines your development workflow. By following the steps outlined in this guide, you can leverage the power of FastAPI and Docker, making it easier to build and deploy robust applications.
Now, go ahead and deploy your FastAPI application on Azure, and unlock the potential of modern web development!