Sobes.tech
Middle

What is the difference between deployment and stateful set in Kubernetes?

sobes.tech AI

Answer from AI

Deployment provides declarative updates for Pods and ReplicaSets. Its main purpose is to manage stateless applications. Pods created by Deployment are identical and interchangeable. During scaling or updates, Pods can be completely replaced with new ones. It does not guarantee the preservation of Pod identity (name, network identity) or the order of their creation/deletion. Used for web servers, microservices without persistent state.

StatefulSet is designed for managing stateful applications. It provides stable network identity, stable persistent storage, and strictly ordered deployment/scaling/deletion of Pods. Each Pod in StatefulSet has a unique, stable hostname (e.g., <statefulset-name>-<ordinal-index>) and is linked to a PersistentVolumeClaim, which guarantees data persistence. Suitable for databases (PostgreSQL, MySQL), distributed systems (Kafka, ZooKeeper).

Main differences are summarized in the table:

Characteristic Deployment StatefulSet
Application Type Stateless Stateful
Pod Identity Non-unique, interchangeable Unique, stable (hostname, ID)
Creation/Deletion Order Arbitrary Strictly ordered by index
Data Storage Temporary, no persistence guaranteed Stable, persistent (via PVC)
Network Identity Arbitrary, changes upon Pod replacement Stable, preserved (via Headless Service)
Scaling Parallel Sequential, in order

Example Manifest for StatefulSet:

apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: my-stateful-app
spec:
  serviceName: "my-stateful-service" # Headless Service
  replicas: 3
  selector:
    matchLabels:
      app: my-stateful-app
  template:
    metadata:
      labels:
        app: my-stateful-app
    spec:
      containers:
      - name: my-container
        image: my-image:latest
        ports:
        - containerPort: 80
        volumeMounts:
        - name: my-persistent-storage
          mountPath: /data # Mount path in container
  volumeClaimTemplates: # Template for creating PersistentVolumeClaim
  - metadata:
      name: my-persistent-storage # Volume name as in volumeMounts
    spec:
      accessModes: [ "ReadWriteOnce" ]
      storageClassName: "standard" # Storage class (e.g., "standard")
      resources:
        requests:
          storage: 1Gi # Requested storage size

Example Manifest for Deployment:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-stateless-app
spec:
  replicas: 3
  selector:
    matchLabels:
      app: my-stateless-app
  template:
    metadata:
      labels:
        app: my-stateless-app
    spec:
      containers:
      - name: my-container
        image: my-image:latest
        ports:
        - containerPort: 80