Deploy a FastAPI application with Dapr on Kubernetes

Deploy a FastAPI application with Dapr on Kubernetes


To deploy a FastAPI application with Dapr on Kubernetes, follow these steps:

1. Install Dapr on your Kubernetes cluster using Helm:

helm upgrade --install dapr dapr/dapr \

--version=1.10 \

--namespace dapr-system \

--create-namespace \

--set global.ha.enabled=true \

--wait        

2. Deploy a Redis component for state management:

Create a file named `redis.yaml` with the following content:


apiVersion: dapr.io/v1alpha

kind: Component

metadata:

?name: statestore

?namespace: default

spec:

?type: state.redis

?version: v1

?metadata:

?- name: redisHost

??value: <REDIS-HOST>

?- name: redisPassword

??value: <REDIS-PASSWORD>

?- name: actorStateStore

??value: "true"1        

Replace `<REDIS-HOST>` and `<REDIS-PASSWORD>` with your Redis instance details, then apply the component to your cluster:

kubectl apply -f redis.yaml        


3. Create a FastAPI application with Dapr:

Install the Dapr FastAPI extension:

pip install dapr-ext-fastapi        

Create a FastAPI app, `app.py`:


from fastapi import FastAP

from dapr.ext.fastapi import DaprClient




app = FastAPI()

dapr_client = DaprClient(app)




@app.post("/order")

async def create_order(order: dict):

??await dapr_client.save_state("statestore", "order", order)

??return {"success": True}




@app.get("/order")

async def get_order():

??order = await dapr_client.get_state("statestore", "order")

??return orderI        

4. Create a Dockerfile for your FastAPI app:


FROM python:3.




WORKDIR /app




COPY requirements.txt .

RUN pip install --no-cache-dir -r requirements.txt




COPY . .




EXPOSE 8000




CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000"]9        

5. Build and push your Docker image:

Replace `<YOUR-DOCKER-REPO>` with your Docker repository.

docker build -t <YOUR-DOCKER-REPO>/fastapi-dapr 

docker push <YOUR-DOCKER-REPO>/fastapi-dapr.        

6. Deploy your FastAPI application with Dapr sidecar:

Create a file named `server.yaml` with the following content:


apiVersion: apps/v

kind: Deployment

metadata:

?name: fastapi-dapr

?labels:

??app: fastapi-dapr

spec:

?replicas: 1

?selector:

??matchLabels:

???app: fastapi-dapr

?template:

??metadata:

???labels:

????app: fastapi-dapr

???annotations:

????dapr.io/enabled: "true"

????dapr.io/app-id: "fastapi-dapr"

????dapr.io/app-port: "8000"

??spec:

???containers:

???- name: fastapi-dapr

????image: <YOUR-DOCKER-REPO>/fastapi-dapr

????ports:

????- containerPort: 80001        

Replace `<YOUR-DOCKER-REPO>` with your Docker repository, then apply the deployment to your cluster:

kubectl apply -f server.yaml        

Now you have a FastAPI application running with Dapr on Kubernetes. You can test your application by making POST and GET requests to the `/order` endpoint.

要查看或添加评论,请登录

Ibrahim Timor的更多文章

社区洞察

其他会员也浏览了