<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Afrozar</title>
    <description>The latest articles on DEV Community by Afrozar (@afrozar).</description>
    <link>https://dev.to/afrozar</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F218490%2Faeac0839-963e-445d-8ec2-35d4aba128e0.jpeg</url>
      <title>DEV Community: Afrozar</title>
      <link>https://dev.to/afrozar</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/afrozar"/>
    <language>en</language>
    <item>
      <title>How To Deploy FastAPI App in Your Local Kubernetes Cluster</title>
      <dc:creator>Afrozar</dc:creator>
      <pubDate>Tue, 04 Jun 2024 10:00:42 +0000</pubDate>
      <link>https://dev.to/afrozar/how-to-deploy-fastapi-app-in-your-local-kubernetes-cluster-1ag5</link>
      <guid>https://dev.to/afrozar/how-to-deploy-fastapi-app-in-your-local-kubernetes-cluster-1ag5</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;You are a developer and containerization holds no secrets for you, and you're looking to advance to the next level. In this tutorial, we will explore how to master container orchestration with Kubernetes. We will learn how to deploy a FastAPI app on the local Kubernetes cluster.&lt;/p&gt;

&lt;p&gt;We will start by showing the source code of our example application with FastAPI. Next, we will create the Docker image that will be used to run the application. After that, we will move on to the step of creating the Kubernetes cluster, and we will finish the tutorial with the deployment and visualization of the results.&lt;/p&gt;

&lt;h2&gt;
  
  
  Prerequisites:
&lt;/h2&gt;

&lt;p&gt;You must already have Docker-Destop installed in your machine.&lt;/p&gt;

&lt;p&gt;You need to be familiar with containerization using Docker and have a basic understanding of Kubernetes concepts.&lt;/p&gt;

&lt;h2&gt;
  
  
  Creating a docker image for our FastAPI App:
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Prepare FastAPI code source:
&lt;/h3&gt;

&lt;p&gt;We will use a basic example of an API to simulate the FastAPI application for our tutorial. This is an API that will get or post users.&lt;/p&gt;

&lt;p&gt;myproject/app/main.py:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from typing import List

from fastapi import FastAPI, APIRouter, HTTPException
from pydantic import BaseModel, Field

app = FastAPI()


user_router = APIRouter(
    prefix='/users'
)


class User(BaseModel):
    id: int = Field(gt=0)
    name: str = Field(max_length=250)


mock_users = [
    {'id': 1, 'name': "Jean Ton"},
    {'id': 2, 'name': "Jean Toto"}
]


@user_router.get('/')
async def get_users() -&amp;gt; List[User]:
    users = [User(**user) for user in mock_users]
    return users


@user_router.get('/{user_id}')
async def get_user(user_id: int):
    user = next((User(**user) for user in mock_users if user['id'] == user_id), None)
    if user is None:
        raise HTTPException(status_code=404, detail='User Not Found')

    return user


@user_router.post('/', response_model=User, status_code=201)
async def add_user(user: User) -&amp;gt; User:

    if any(existing_user['id'] == user.id for existing_user in mock_users):
        raise HTTPException(status_code=400, detail="User already exists")

    mock_users.append(user.dict())

    return user


app.include_router(user_router)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;myproject/requirements.txt:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fastapi==0.111.0

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Build and push the docker image:
&lt;/h3&gt;

&lt;p&gt;The next step is to create the docker image to be used to run FastAPI app&lt;/p&gt;

&lt;h4&gt;
  
  
  Build the image:
&lt;/h4&gt;

&lt;p&gt;We will use the following Dockerfile:&lt;/p&gt;

&lt;p&gt;myproject/Dockerfile:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;FROM python:3.9

WORKDIR /code

COPY ./requirements.txt /code/requirements.txt

RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt

COPY ./app /code/app

EXPOSE 80

CMD ["fastapi", "run", "app/main.py", "--port", "80"]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Run this command to create the image:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;docker build . -t kubernetes-fastapi-app-img

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Push the image to a private registry:
&lt;/h4&gt;

&lt;p&gt;When deploying a Kubernetes application, you typically specify the container image that Kubernetes should pull from a container registry. However, if you want to use a local image (one that is not in a registry), you can use a few methods.&lt;/p&gt;

&lt;p&gt;These are some methods to use local images in Kubernetes:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Using Minikube or Kind (Kubernetes in Docker):&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Both Minikube and Kind allow you to use local Docker images directly. You can load the image into the Minikube or Kind environment.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Using a Private Registry:&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;If you are not using Minikube or Kind, you can set up a local Docker registry to which you push your image, and then configure Kubernetes to pull from this registry.&lt;/p&gt;

&lt;p&gt;For this tutorial, we will use a private registry that we will run locally using the follwing command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;docker run -d -p 5000:5000 --name registry registry:2

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then we will tag the image:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;docker tag kubernetes-fastapi-app-img:latest localhost:5000/kubernetes-fastapi-app-img:latest
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Push the image to your local registry:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;docker push localhost:5000/kubernetes-fastapi-app-img:latest
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Create Kubernetes cluser:
&lt;/h3&gt;

&lt;p&gt;Now that our FastAPI docker image is ready in the registry, let's install the Kubernetes cluser:&lt;/p&gt;

&lt;p&gt;Open your Docker-desktop, go to Settings &amp;gt;&amp;gt; Kubernetes, then select the option 'Enable Kubernetes'. This will install all the necessary ressources for functional Kubernetes Cluser.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvkox27a42yyghc2li74x.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvkox27a42yyghc2li74x.png" alt="How to enable Kubernetes in Docker-desktop" width="800" height="452"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;To check if Kubernetes is installed and is running, open your terminal and type the command &lt;code&gt;kubectl&lt;/code&gt;. Everything is fine if the output starts with &lt;code&gt;kubectl controls the Kubernetes cluster manager&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Deployment file:
&lt;/h3&gt;

&lt;p&gt;The next step is to deploy our image in Kubernetes. For this, we need to create a YAML file that will contain the deployment configuration.:&lt;/p&gt;

&lt;p&gt;myproject/deploy/deploy.yaml&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;apiVersion: apps/v1
kind: Deployment
metadata:
  name: fastapi-deployment
  labels:
    app: fastapi
spec:
  replicas: 1
  selector:
    matchLabels:
      app: fastapi
  template:
    metadata:
      labels:
        app: fastapi
    spec:
      containers:
      - name: fastapi
        image: localhost:5000/kubernetes-fastapi-app-img
        ports:
        - containerPort: 80
        env:
        - name: ENVIRONMENT
          value: "testing"

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

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This Kubernetes YAML file defines a Deployment resource for deploying our FastAPI application. Below is a brief explanation of key parts of the file:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Deployment Name: fastapi-deployment&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Labels: app: fastapi for both the deployment and its pods.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Replicas: 1 instance (pods) of the FastAPI application.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Container Image: The container uses an image from a local registry (localhost:5000/kubernetes-fastapi-app-img).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Container Port: The container listens on port 80.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Apply the deployment configuation to Kubernetes cluster:
&lt;/h3&gt;

&lt;p&gt;Firstly, make sure that the current context is set to &lt;code&gt;docker-desktop&lt;/code&gt; using:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;kubectl config current-context
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If that's not the case, you can switch to &lt;code&gt;docker-desktop&lt;/code&gt; using the following command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;kubectl config use-context docker-desktop
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, we are ready to apply our deployment file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;kubectl apply -f deploy\deploy.yaml
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Feco7amdvi1vko6t4stad.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Feco7amdvi1vko6t4stad.png" alt="Apply deployment output" width="467" height="64"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Use the command bellow to see the status of the created pod:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;kubectl get pods
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftc905eukhgkv6rpxnv0z.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftc905eukhgkv6rpxnv0z.png" alt="Getting pods" width="780" height="71"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We can show logs of our created pod:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;kubectl logs fastapi-deployment-8fc7dd7d-z45k4
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvkaner6xb5qm8tfb2ggm.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvkaner6xb5qm8tfb2ggm.png" alt="Pod logs" width="800" height="582"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Our API swagger is accessible locally via &lt;a href="http://localhost/docs"&gt;http://localhost/docs&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fuv68445ngqkgj26x2dvp.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fuv68445ngqkgj26x2dvp.png" alt="FastAPI API Swagger" width="800" height="362"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;This tutorial is primarily aimed at developers who want to deploy their applications on Kubernetes, but it can also be useful for those who want to deploy their applications on remote Kubernetes clusters, such as those on Azure or AWS.&lt;/p&gt;

&lt;p&gt;I would be delighted to see your comments or answer your questions.&lt;/p&gt;

</description>
      <category>kubernetes</category>
      <category>fastapi</category>
      <category>python</category>
      <category>tutorial</category>
    </item>
  </channel>
</rss>
