Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy
Kubernetes

Kubernetes: StatefulSets for Database Deployments

- 25.07.26 - ErcanOPAK

🗄️ StatefulSets = Database on Kubernetes

Databases need special handling. StatefulSets provide stable storage and network identities for stateful applications like databases.

📝 PostgreSQL StatefulSet Configuration

apiVersion: v1
kind: Secret
metadata:
    name: postgres-secret
type: Opaque
data:
    postgres-password: c2VjcmV0X3Bhc3N3b3Jk
---
apiVersion: v1
kind: ConfigMap
metadata:
    name: postgres-config
data:
    postgresql.conf: |
        max_connections = 100
        shared_buffers = 256MB
        effective_cache_size = 1GB
        work_mem = 16MB
        maintenance_work_mem = 128MB
        checkpoint_completion_target = 0.9
        wal_buffers = 16MB
        default_statistics_target = 100
---
apiVersion: v1
kind: Service
metadata:
    name: postgres
    labels:
        app: postgres
spec:
    selector:
        app: postgres
    ports:
    - port: 5432
        name: postgres
    clusterIP: None
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
    name: postgres
spec:
    serviceName: postgres
    replicas: 3
    selector:
        matchLabels:
            app: postgres
    template:
        metadata:
            labels:
                app: postgres
        spec:
            containers:
            - name: postgres
                image: postgres:15
                env:
                - name: POSTGRES_PASSWORD
                    valueFrom:
                        secretKeyRef:
                            name: postgres-secret
                            key: postgres-password
                - name: PGDATA
                    value: /var/lib/postgresql/data/pgdata
                - name: POSTGRES_INITDB_ARGS
                    value: --data-checksums
                ports:
                - containerPort: 5432
                    name: postgres
                volumeMounts:
                - name: postgres-storage
                    mountPath: /var/lib/postgresql/data
                - name: postgres-config
                    mountPath: /etc/postgresql
                resources:
                    requests:
                        memory: 512Mi
                        cpu: 500m
                    limits:
                        memory: 1Gi
                        cpu: 1000m
                livenessProbe:
                    exec:
                        command:
                        - /bin/sh
                        - -c
                        - pg_isready -U postgres
                    initialDelaySeconds: 30
                    periodSeconds: 10
                    timeoutSeconds: 5
                readinessProbe:
                    exec:
                        command:
                        - /bin/sh
                        - -c
                        - pg_isready -U postgres
                    initialDelaySeconds: 10
                    periodSeconds: 5
                    timeoutSeconds: 3
            volumes:
            - name: postgres-config
                configMap:
                    name: postgres-config
    volumeClaimTemplates:
    - metadata:
            name: postgres-storage
        spec:
            accessModes: [ ReadWriteOnce ]
            resources:
                requests:
                    storage: 50Gi
            storageClassName: standard

🎯 Database Operations on StatefulSets

# Access PostgreSQL
# Connect to primary pod
kubectl exec -it postgres-0 -- psql -U postgres

# Get pod information
kubectl get pods -l app=postgres -o wide

# Check replication status
kubectl exec -it postgres-0 -- psql -U postgres -c SELECT * FROM pg_stat_replication;

# Backup database
kubectl exec -it postgres-0 -- pg_dump -U postgres mydb > backup.sql

# Restore database
kubectl exec -i postgres-0 -- psql -U postgres mydb < backup.sql

# Increase replicas
kubectl scale statefulset postgres --replicas=5

# Rolling Update
kubectl patch statefulset postgres --type='json' -p='[{"op": "replace", "path": "/spec/template/spec/containers/0/image", "value":"postgres:15.1"}]'

# View persistent volumes
kubectl get pvc

# Manual failover
kubectl delete pod postgres-0
# Kubernetes will recreate with same storage

# Migration Script
kubectl exec -it postgres-0 -- psql -U postgres <

💡 StatefulSet Best Practices

  • Use separate storage class for databases
  • Implement regular backup schedule
  • Use pod anti-affinity for high availability
  • Monitor disk usage and performance
  • Test failover procedures regularly

StatefulSets bring the power of Kubernetes to stateful applications. With proper configuration, you get high availability and scalability for your databases.

— Database Administrator

Related posts:

Kubernetes: Use ConfigMaps for Configuration Management

Kubernetes: Use ConfigMaps for Configuration Management

Kubernetes: Configure Liveness, Readiness, and Startup Probes

Kubernetes: Configure Liveness, Readiness, and Startup Probes

Kubernetes Pods Restart Without Errors

Kubernetes Pods Restart Without Errors

Views: 9

Post navigation

WordPress: Optimize Database for Membership Sites
Docker: Implement Log Rotation and Retention Policies

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

November 2026
M T W T F S S
 1
2345678
9101112131415
16171819202122
23242526272829
30  
« Oct    

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,055)
  • Get the User Name and Domain Name from an Email Address in SQL (981)
  • How to add default value for Entity Framework migrations for DateTime and Bool (977)
  • Get the First and Last Word from a String or Sentence in SQL (858)
  • How to select distinct rows in a datatable in C# (854)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (653)
  • Add Constraint to SQL Table to ensure email contains @ (609)
  • Average of all values in a column that are not zero in SQL (570)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (547)
  • Find numbers with more than two decimal places in SQL (475)

Recent Posts

  • C#: Fix a ConditionalWeakTable Entry Vanishing Too Soon
  • Docker: Fix a Stale COPY Layer After Editing .dockerignore
  • Photoshop: Fix a Pattern Overlay Scaling Wrong on a High-DPI File
  • SQL Server: Fix a Computed Column Index Skipped by Implicit Cast
  • HTML5: Fix a required Input Inside a Hidden Tab Blocking Submit
  • SQL Server: Fix ROW_NUMBER Ties Reordering Between Identical Runs
  • C#: Fix an Enum HasFlag Returning True for the Zero Value
  • WordPress: Fix Featured Images Vanishing After a CDN Migration
  • Photoshop: Fix Content-Aware Fill Smearing a Repeating Pattern
  • Asp.Net Core: Fix Antiforgery Tokens Rejected Behind a Reverse Proxy

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,055)
  • Get the User Name and Domain Name from an Email Address in SQL (981)
  • How to add default value for Entity Framework migrations for DateTime and Bool (977)
  • Get the First and Last Word from a String or Sentence in SQL (858)
  • How to select distinct rows in a datatable in C# (854)

Recent Posts

  • C#: Fix a ConditionalWeakTable Entry Vanishing Too Soon
  • Docker: Fix a Stale COPY Layer After Editing .dockerignore
  • Photoshop: Fix a Pattern Overlay Scaling Wrong on a High-DPI File
  • SQL Server: Fix a Computed Column Index Skipped by Implicit Cast
  • HTML5: Fix a required Input Inside a Hidden Tab Blocking Submit

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com