Cloud Technology Community Question

Should I use StatefulSets or Deployments for my database on K8s?

Posted on 2024-11-12 • In Cloud Technology • By Christopher Garcia

I am planning to move our MongoDB and PostgreSQL instances into our Kubernetes cluster to simplify our CI/CD pipeline. However, I’m confused about whether I should use a standard Deployment or a StatefulSet. What are the key differences in how Kubernetes handles storage, networking, and scaling for these two types of resources when dealing with persistent data?

3 Answers 11,473 Views

All answers to this question 3 Answers

Dorothy Martinez Answered on 2024-11-14
Answered

For databases, you should almost always use StatefulSets. Unlike Deployments, StatefulSets provide a stable, unique network identifier for each pod (e.g., pod-0, pod-1), which is crucial for database clustering and replication. They also ensure that when a pod is rescheduled, it reconnects to the same Persistent Volume (PV). In a Deployment, pods are interchangeable and storage is shared, which can lead to data corruption if multiple pods try to write to the same volume simultaneously. StatefulSets handle the ordered, graceful deployment and scaling required for stateful apps.

Richard Moore Answered on 2024-11-15
Answered

What kind of storage class are you using? Even with a StatefulSet, the underlying storage needs to support the specific access modes (like ReadWriteOnce) required by your database to ensure consistency.

Christopher Garcia Commented on 2024-11-16
Commented

Richard, we are using AWS EBS with the gp3 storage class. It supports ReadWriteOnce, which fits the StatefulSet model perfectly. I was worried about how the secondary nodes would find the primary after a restart, but Dorothy's explanation about the stable network ID via a Headless Service cleared that up. We'll be setting up a Headless Service today to manage the DNS for our Mongo members.

Margaret White Answered on 2024-11-17
Answered

StatefulSets also give you ordered updates. This means it updates one pod at a time, ensuring your database cluster doesn't lose its quorum during a rollout.

Dorothy Martinez Commented on 2024-11-18
Commented

Exactly. Margaret’s point about quorum is why we use StatefulSets for our ETCD and Consul clusters too. It's much safer than a rolling update in a Deployment.

Write a Comment

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

Join the LearnersEra Community

Ask questions, share knowledge and learn from professionals across technology, project management and certification topics.

Change Country and Nearest City

Select your country and nearest city to see courses available in your region.