8-how-to-deploy-a-fastapi-application-using-docker-and-kubernetes.html

How to Deploy a FastAPI Application Using Docker and Kubernetes

Deploying applications in a modern development environment often requires the use of containerization and orchestration tools. FastAPI is a high-performance web framework for building APIs with Python, and it pairs seamlessly with Docker and Kubernetes to create scalable and efficient applications. In this article, we will guide you through the process of deploying a FastAPI application using Docker and Kubernetes, complete with clear code examples and actionable insights.

What is FastAPI?

FastAPI is an easy-to-use, high-performance web framework for building APIs with Python 3.6+ based on standard Python type hints. It is designed to be fast, allowing developers to create APIs that are quick to respond and easy to maintain. FastAPI comes with built-in validation, interactive documentation, and automatic generation of API documentation.

Use Cases of FastAPI

FastAPI is suitable for various applications, including:

  • RESTful APIs
  • Microservices
  • Data processing applications
  • Machine learning model serving
  • Real-time web applications

Setting Up Your FastAPI Application

Before diving into Docker and Kubernetes, let’s create a simple FastAPI application.

Step 1: Create a FastAPI Application

First, ensure you have Python installed. You can create a virtual environment to manage dependencies.

# Create a virtual environment
python -m venv fastapi-env
source fastapi-env/bin/activate  # On Windows use `fastapi-env\Scripts\activate`

# Install FastAPI and Uvicorn
pip install fastapi uvicorn

Create a file named main.py and add the following code:

from fastapi import FastAPI

app = FastAPI()

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

@app.get("/items/{item_id}")
async def read_item(item_id: int, q: str = None):
    return {"item_id": item_id, "query": q}

Step 2: Test Locally

Run your FastAPI application locally using Uvicorn:

uvicorn main:app --reload

Open your browser and navigate to http://127.0.0.1:8000, where you should see the JSON response {"Hello": "World"}. You can also access the interactive documentation at http://127.0.0.1:8000/docs.

Containerizing Your FastAPI Application with Docker

Step 3: Create a Dockerfile

To deploy your FastAPI application using Docker, you need to create a Dockerfile. This file contains the instructions for building your Docker image.

Create a file named Dockerfile in the same directory as main.py:

# Use the official Python image
FROM python:3.9

# Set the working directory
WORKDIR /app

# Copy the requirements file and install dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# Copy the application code
COPY . .

# Expose the port
EXPOSE 8000

# Command to run the application
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]

Step 4: Create a Requirements File

Next, create a requirements.txt file to list the dependencies:

fastapi
uvicorn

Step 5: Build the Docker Image

Now, build the Docker image using the following command:

docker build -t fastapi-app .

Step 6: Run the Docker Container

Run your FastAPI application in a Docker container:

docker run -d -p 8000:8000 fastapi-app

You can access the application again at http://localhost:8000.

Deploying Your FastAPI Application Using Kubernetes

With your FastAPI application containerized, you can now deploy it using Kubernetes.

Step 7: Create a Kubernetes Deployment

First, ensure you have a Kubernetes cluster running. You can use Minikube for local testing. Create a file named deployment.yaml:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: fastapi-deployment
spec:
  replicas: 3
  selector:
    matchLabels:
      app: fastapi
  template:
    metadata:
      labels:
        app: fastapi
    spec:
      containers:
      - name: fastapi-container
        image: fastapi-app:latest
        ports:
        - containerPort: 8000

Step 8: Create a Kubernetes Service

To expose your FastAPI application, create a service. Add the following to a file named service.yaml:

apiVersion: v1
kind: Service
metadata:
  name: fastapi-service
spec:
  selector:
    app: fastapi
  ports:
    - protocol: TCP
      port: 80
      targetPort: 8000
  type: LoadBalancer

Step 9: Deploy to Kubernetes

Now, deploy the application and service to your Kubernetes cluster:

kubectl apply -f deployment.yaml
kubectl apply -f service.yaml

Step 10: Access Your Application

To find your service’s external IP address, run:

kubectl get services

Once the external IP is assigned, you can access your FastAPI application via that IP.

Troubleshooting Common Issues

  • Image Not Found: Ensure you build your Docker image correctly and tag it as fastapi-app:latest.
  • Port Issues: Check that the ports in your Dockerfile and Kubernetes service are correctly configured.
  • Kubernetes Not Responding: Verify that your Kubernetes cluster is running and that the pods are in a healthy state using kubectl get pods.

Conclusion

Deploying a FastAPI application using Docker and Kubernetes allows for efficient management and scaling of your APIs. By following the steps outlined in this article, you can easily containerize your application and deploy it within a Kubernetes environment, ready for production. Whether you are building microservices or robust APIs, leveraging these modern tools will enhance your development workflow and application performance. Happy coding!

SR
Syed
Rizwan

About the Author

Syed Rizwan is a Machine Learning Engineer with 5 years of experience in AI, IoT, and Industrial Automation.