minikube로 fastapi 배포

code_able·2024년 7월 16일
0
post-custom-banner

사용하는 기기 정보

Rasberry pi5
ubuntu 23.10

fastapi 코드 만들기

프로젝트세팅

pip install poetry
poetry new fastapi-ml

fastapi-ml
├── app
├──── __init__.py
├──── main.py
├── tests
├──── __init__.py
├── Dockerfile
├── poetry.lock
├── project.toml
├── README.md

main.py 작성

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.get("/check")
def check():
    return "success"

dockerfile 작성

FROM python:3.11.6-slim

RUN mkdir -p /app
COPY . /app/
WORKDIR /app

RUN pip3 install poetry
# poetry lock에서 requirements.txt 생성
RUN poetry export -f requirements.txt --output requirements.txt --without-hashes
RUN pip3 install --no-cache-dir -r requirements.txt

# app 실행
CMD gunicorn app.main:app --bind 0.0.0.0:8000 -w 3 -k uvicorn.workers.UvicornWorker

docker hub 배포

docker build -t stygj/fastapi-ml:0.0.1 .
docker push stygj/fastapi-ml:0.0.1

minikube 설치

curl -LO https://storage.googleapis.com/minikube/releases/latest/minikube-linux-arm64
sudo install minikube-linux-arm64 /usr/local/bin/minikube && rm minikube-linux-arm64

minikube 시작

minikube start

deployment 만들기

fastapi-ml-deployment.yaml 작성

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

실행

kubectl apply -f fastapi-ml-deployment.yaml

service 만들기

fastapi-ml-service.yaml 작성

apiVersion: v1
kind: Service
metadata:
  name: fastapi-ml-service
  labels:
    name: fastapi-ml
spec:
  selector:
    app: fastapi-ml
  type: NodePort
  ports:
  - port: 8000
    targetPort: 8000
    name: http
    protocol: TCP

실행

kubectl apply -f fastapi-ml-service.yaml
minikube service fastapi-ml-service --url

kubectl get service
kubectl describe svc/fastapi-ml-service

테스트

kubectl get pods
kubectl logs -f [podsname]

kubectl port-forward svc/fastapi-ml-service --address=0.0.0.0 8000:8000
curl -XGET http://127.0.0.1:8000/check

ingress 만들기

fastapi-ml-ingress.yaml 작성

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: fastapi-ml-ingress
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /
spec:
  rules:
  - http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: fastapi-ml-service
            port:
              number: 8000

실행

kubectl apply -f fastapi-ml-ingress.yaml

kubectl get ingess
kubectl describe ingress fastapi-ml-ingress

테스트

minikube ip -> 192.168.49.2
curl -XGET http://192.168.49.2/check
profile
할수 있다! code able
post-custom-banner

0개의 댓글