<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Priyanka Sharma on Medium]]></title>
        <description><![CDATA[Stories by Priyanka Sharma on Medium]]></description>
        <link>https://medium.com/@priyanka.kapie35?source=rss-b86010ceff39------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*7td41--JLlzfr4sN.jpg</url>
            <title>Stories by Priyanka Sharma on Medium</title>
            <link>https://medium.com/@priyanka.kapie35?source=rss-b86010ceff39------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 17:08:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@priyanka.kapie35/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building Scalable Stateful Applications on Kubernetes: A Practical Guide]]></title>
            <link>https://medium.com/@priyanka.kapie35/building-scalable-stateful-applications-on-kubernetes-a-practical-guide-544f632eb839?source=rss-b86010ceff39------2</link>
            <guid isPermaLink="false">https://medium.com/p/544f632eb839</guid>
            <dc:creator><![CDATA[Priyanka Sharma]]></dc:creator>
            <pubDate>Thu, 29 Aug 2024 13:10:12 GMT</pubDate>
            <atom:updated>2024-08-29T13:10:12.793Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/284/1*OL367x0E-HmsaR47lab1KA.jpeg" /></figure><p>In today’s cloud-native world, Kubernetes has become the go-to platform for deploying and managing containerized applications. One of the powerful features of Kubernetes is its ability to handle stateful applications with persistent storage and scale them efficiently using Horizontal Pod Autoscalers (HPA). In this blog post, we will explore how to deploy a stateful database using StatefulSets, create an API service that accesses this database, and scale the API service using HPA.</p><h3>Introduction</h3><p>Kubernetes provides powerful abstractions for managing containerized applications, including StatefulSets for stateful applications and Horizontal Pod Autoscalers (HPA) for dynamic scaling. In this guide, we will deploy a PostgreSQL database using a StatefulSet, create a Flask API service to interact with the database, and implement HPA to ensure our API service can handle varying loads efficiently.</p><h3>Prerequisites</h3><p>Before we begin, ensure you have the following:</p><ul><li>A Kubernetes cluster (e.g., Minikube, EKS, GKE, AKS)</li><li>kubectl configured to interact with your cluster</li><li>Docker (for building the API image)</li></ul><h3>Deploying the Stateful Database</h3><h3>ConfigMaps and Secrets</h3><p>First, we need to create a ConfigMap and a Secret to store the PostgreSQL configuration and credentials.</p><p><strong>postgres-config.yaml</strong></p><pre>apiVersion: v1<br>kind: ConfigMap<br>metadata:<br>  name: postgres-config<br>data:<br>  postgres-host: postgres<br>  postgres-db: mydatabase</pre><p><strong>postgres-secret.yaml</strong></p><pre>apiVersion: v1<br>kind: Secret<br>metadata:<br>  name: postgres-secret<br>type: Opaque<br>data:<br>  postgres-user: cG9zdGdyZXM=<br>  postgres-password: cGFzc3dvcmQ=</pre><h3>Persistent Volumes and Persistent Volume Claims</h3><p>Next, define the Persistent Volume (PV) and Persistent Volume Claim (PVC) for data persistence.</p><p><strong>postgres-pv.yaml</strong></p><pre>apiVersion: v1<br>kind: PersistentVolume<br>metadata:<br>  name: postgres-pv<br>spec:<br>  capacity:<br>    storage: 2Gi<br>  accessModes:<br>    - ReadWriteOnce<br>  hostPath:<br>    path: &quot;/mnt/data&quot;</pre><p><strong>postgres-pvc.yaml</strong></p><pre>apiVersion: v1<br>kind: PersistentVolumeClaim<br>metadata:<br>  name: postgres-pvc<br>spec:<br>  accessModes:<br>    - ReadWriteOnce<br>  resources:<br>    requests:<br>      storage: 2Gi</pre><h3>StatefulSet</h3><p>Deploy the PostgreSQL StatefulSet.</p><p><strong>postgres-statefulset.yaml</strong></p><pre>apiVersion: apps/v1<br>kind: StatefulSet<br>metadata:<br>  name: postgres<br>spec:<br>  serviceName: &quot;postgres&quot;<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      app: postgres<br>  template:<br>    metadata:<br>      labels:<br>        app: postgres<br>    spec:<br>      containers:<br>      - name: postgres<br>        image: postgres:13<br>        ports:<br>        - containerPort: 5432<br>          name: postgres<br>        env:<br>        - name: POSTGRES_USER<br>          valueFrom:<br>            secretKeyRef:<br>              name: postgres-secret<br>              key: postgres-user<br>        - name: POSTGRES_PASSWORD<br>          valueFrom:<br>            secretKeyRef:<br>              name: postgres-secret<br>              key: postgres-password<br>        - name: POSTGRES_DB<br>          valueFrom:<br>            configMapKeyRef:<br>              name: postgres-config<br>              key: postgres-db<br>        volumeMounts:<br>        - name: postgres-storage<br>          mountPath: /var/lib/postgresql/data<br>  volumeClaimTemplates:<br>  - metadata:<br>      name: postgres-storage<br>    spec:<br>      accessModes: [ &quot;ReadWriteOnce&quot; ]<br>      resources:<br>        requests:<br>          storage: 2Gi</pre><p>Apply these configurations:</p><pre>kubectl apply -f postgres-config.yaml<br>kubectl apply -f postgres-secret.yaml<br>kubectl apply -f postgres-pv.yaml<br>kubectl apply -f postgres-pvc.yaml<br>kubectl apply -f postgres-statefulset.yaml</pre><h3>4. Deploying the API Service</h3><h3>API Deployment</h3><p>Create a simple Flask application that connects to the PostgreSQL database. Build a Docker image for the Flask API and push it to your container registry.</p><p><strong>Dockerfile</strong></p><pre>FROM python:3.9-slim</pre><pre>WORKDIR /app</pre><pre>COPY requirements.txt requirements.txt<br>RUN pip install -r requirements.txt</pre><pre>COPY app.py app.py</pre><pre>CMD [&quot;python&quot;, &quot;app.py&quot;]</pre><p><strong>requirements.txt</strong></p><pre>flask<br>psycopg2-binary</pre><p><strong>app.py</strong></p><pre>from flask import Flask, jsonify<br>import os<br>import psycopg2</pre><pre>app = Flask(__name__)</pre><pre>def get_db_connection():<br>    conn = psycopg2.connect(<br>        host=os.getenv(&#39;POSTGRES_HOST&#39;),<br>        database=os.getenv(&#39;POSTGRES_DB&#39;),<br>        user=os.getenv(&#39;POSTGRES_USER&#39;),<br>        password=os.getenv(&#39;POSTGRES_PASSWORD&#39;)<br>    )<br>    return conn</pre><pre>@app.route(&#39;/data&#39;)<br>def get_data():<br>    conn = get_db_connection()<br>    cur = conn.cursor()<br>    cur.execute(&#39;SELECT * FROM test_table;&#39;)<br>    rows = cur.fetchall()<br>    cur.close()<br>    conn.close()<br>    return jsonify(rows)</pre><pre>if __name__ == &#39;__main__&#39;:<br>    app.run(host=&#39;0.0.0.0&#39;, port=5000)</pre><p>Build and push the Docker image:</p><pre>docker build -t your-docker-username/flask-api:latest .<br>docker push your-docker-username/flask-api:latest</pre><p>Deploy the Flask API service with a Deployment and Service.</p><p><strong>flask-deployment.yaml</strong></p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: flask-app<br>spec:<br>  replicas: 3<br>  selector:<br>    matchLabels:<br>      app: flask-app<br>  template:<br>    metadata:<br>      labels:<br>        app: flask-app<br>    spec:<br>      containers:<br>      - name: flask-app<br>        image: your-docker-username/flask-api:latest<br>        ports:<br>        - containerPort: 5000<br>        env:<br>        - name: POSTGRES_HOST<br>          valueFrom:<br>            configMapKeyRef:<br>              name: postgres-config<br>              key: postgres-host<br>        - name: POSTGRES_DB<br>          valueFrom:<br>            configMapKeyRef:<br>              name: postgres-config<br>              key: postgres-db<br>        - name: POSTGRES_USER<br>          valueFrom:<br>            secretKeyRef:<br>              name: postgres-secret<br>              key: postgres-user<br>        - name: POSTGRES_PASSWORD<br>          valueFrom:<br>            secretKeyRef:<br>              name: postgres-secret<br>              key: postgres-password<br>        resources:<br>          requests:<br>            memory: &quot;12Mi&quot;<br>            cpu: &quot;100m&quot;<br>          limits:<br>            memory: &quot;50Mi&quot;<br>            cpu: &quot;250m&quot;</pre><p><strong>flask-service.yaml</strong></p><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: flask-service<br>spec:<br>  type: LoadBalancer<br>  selector:<br>    app: flask-app<br>  ports:<br>  - protocol: TCP<br>    port: 80<br>    targetPort: 5000</pre><p>Apply these configurations:</p><pre>kubectl apply -f flask-deployment.yaml<br>kubectl apply -f flask-service.yaml</pre><h3>5. Implementing Horizontal Pod Autoscaler (HPA)</h3><p>Create an HPA configuration to scale the Flask API service based on CPU usage.</p><p><strong>hpa.yaml</strong></p><pre>apiVersion: autoscaling/v1<br>kind: HorizontalPodAutoscaler<br>metadata:<br>  name: flask-app-hpa<br>spec:<br>  scaleTargetRef:<br>    apiVersion: apps/v1<br>    kind: Deployment<br>    name: flask-app<br>  minReplicas: 3<br>  maxReplicas: 10<br>  targetCPUUtilizationPercentage: 50</pre><p>Apply the HPA configuration:</p><pre>kubectl apply -f hpa.yaml</pre><h3>6. Testing and Verification</h3><p>To test and verify that the setup works, you can:</p><ol><li><strong>Access the Flask API</strong>: Use the external IP of the flask-service to access the API endpoints.</li><li><strong>Verify Data Persistence</strong>: Connect to the PostgreSQL database and ensure that the data is persisted.</li><li><strong>Test HPA</strong>: Generate load on the Flask API to see the HPA in action. You can use tools like hey or ab to simulate traffic.</li></ol><pre>hey -z 2m -c 100 http://&lt;external-ip&gt;/data</pre><h3>7. Conclusion</h3><p>In this blog post, we covered how to deploy a stateful PostgreSQL database using StatefulSets, create a Flask API service to interact with the database, and implement Horizontal Pod Autoscaling to ensure efficient handling of varying loads. By leveraging Kubernetes features like StatefulSets, ConfigMaps, Secrets, and HPA, we can build scalable and resilient applications that meet production standards.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=544f632eb839" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>