Управление приложениями с состоянием с помощью StatefulSets
Развёртывайте и управляйте приложениями с состоянием, например базами данных, с помощью StatefulSets, обеспечивая стабильные сетевые идентификаторы и постоянное хранилище.
«Управление приложениями с состоянием с помощью StatefulSets» — бесплатный урок Docker & Kubernetes for Developers на CoddyKit. Это урок 2 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Docker & Kubernetes for Developers, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Docker & Kubernetes for Developers содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Stateful Applications in K8s
When deploying applications in Kubernetes, some applications are stateless, meaning they don't store data locally and can be easily scaled or replaced.
However, many critical applications, like databases or message queues, are stateful. They need persistent storage and stable network identities.
This lesson introduces StatefulSets, a Kubernetes API object designed specifically to manage these stateful workloads.
Why StatefulSets?
Traditional Kubernetes Deployments are great for stateless apps. They create Pods with arbitrary names and can replace them freely.
Stateful applications, however, require:
- Stable, unique network identities: Each instance needs a consistent name.
- Stable, persistent storage: Data must survive Pod restarts or rescheduling.
- Ordered deployment and scaling: Sometimes, instances need to start or stop in a specific sequence.
StatefulSets provide these crucial capabilities.
Key Features of StatefulSets
StatefulSets offer several powerful features for managing stateful applications:
- Stable Network ID: Each Pod gets a predictable name (e.g.,
web-0,web-1) and DNS hostname. - Stable Persistent Storage: Integrates with Persistent Volumes (PVs) and Persistent Volume Claims (PVCs) to give each Pod its own persistent storage.
- Ordered Guarantees: Ensures Pods are created, scaled, and deleted in a strict, ordinal order.
- Graceful Deployment: Pods are only created after their storage is ready, and only deleted after they've gracefully shut down.
StatefulSet Components
A StatefulSet typically works in conjunction with other Kubernetes resources:
- Headless Service: Provides stable network identities for the Pods. It doesn't load-balance traffic, but creates unique DNS entries for each Pod.
- Pod Template: Defines the specification for the Pods, including containers, resources, etc.
- Volume Claim Templates: Generates a unique Persistent Volume Claim (PVC) for each Pod, ensuring dedicated storage.
Defining a Headless Service
Before creating a StatefulSet, you often define a Headless Service. This service is crucial for assigning stable network identities to your stateful Pods.
Notice clusterIP: None, which tells Kubernetes not to assign a cluster IP, making it 'headless'.
apiVersion: v1
kind: Service
metadata:
name: my-app-service
labels:
app: my-app
spec:
ports:
- port: 80
name: web
clusterIP: None # This makes it a Headless Service
selector:
app: my-appCreating a Basic StatefulSet
Now, let's look at a basic StatefulSet definition. It links to our Headless Service using serviceName and defines a volumeClaimTemplates for persistent storage.
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: my-app
spec:
serviceName: "my-app-service" # Link to Headless Service
replicas: 3
selector:
matchLabels:
app: my-app
template:
metadata:
labels:
app: my-app
spec:
containers:
- name: my-container
image: nginx
ports:
- containerPort: 80
volumeMounts:
- name: www
mountPath: /usr/share/nginx/html
volumeClaimTemplates:
- metadata:
name: www
spec:
accessModes: [ "ReadWriteOnce" ]
resources:
requests:
storage: 1GiUnderstanding Pod Identity
When the StatefulSet from the previous scene is deployed, it will create three Pods named my-app-0, my-app-1, and my-app-2.
Each Pod also gets its own stable DNS entry, like my-app-0.my-app-service.default.svc.cluster.local. This allows other services to reliably connect to specific instances.
Crucially, each Pod will also get its own unique Persistent Volume Claim (e.g., www-my-app-0), ensuring dedicated storage.
Ordered Deployment & Scaling
StatefulSets enforce a strict order for Pod creation, scaling, and deletion. This is vital for applications where sequence matters (e.g., a primary database and its replicas).
- Creation: Pods are created in ascending ordinal order (
my-app-0, thenmy-app-1, etc.). Each Pod is fully running and ready before the next is created. - Deletion: Pods are terminated in descending ordinal order (
my-app-2, thenmy-app-1, etc.). Each Pod is fully shut down before the next is deleted. - Scaling: Similarly, scaling up adds Pods in order, and scaling down removes them in reverse order.
Updating StatefulSets
StatefulSets support controlled updates to their Pods, typically used for rolling out new versions of your application.
- RollingUpdate (default): Pods are updated in reverse ordinal order (
my-app-2, thenmy-app-1, etc.). Each Pod is updated and ready before the next one starts. - OnDelete: This strategy requires manual intervention. The StatefulSet controller will not automatically update Pods. You must manually delete Pods for the new template to take effect.
Rolling updates ensure minimal downtime and maintain the application's state during upgrades.
StatefulSet Features Check
Which of the following are key characteristics or requirements for Kubernetes StatefulSets?
StatefulSets Recap
Congratulations! You've learned about Kubernetes StatefulSets.
- StatefulSets manage stateful applications, ensuring stable identities and persistent storage.
- They provide stable network IDs, ordered operations, and leverage Volume Claim Templates for dedicated storage.
- A Headless Service is often used to provide stable DNS entries for StatefulSet Pods.
- They support controlled updates with strategies like
RollingUpdate.
StatefulSets are essential for running databases, message queues, and other stateful services reliably on Kubernetes.
Изучай Docker & Kubernetes for Developers с ИИ-репетитором — бесплатно
Пиши и запускай код прямо в браузере, получай мгновенную помощь от ИИ-репетитора 24/7 и продолжи учиться на сайте или в приложении.
- Курсы
- 12
- Уроки
- 48
Часто задаваемые вопросы
Урок «Управление приложениями с состоянием с помощью StatefulSets» бесплатный?
Да — полный текст урока «Управление приложениями с состоянием с помощью StatefulSets» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Docker & Kubernetes for Developers, подпишись на CoddyKit PRO. Курс Docker & Kubernetes for Developers содержит 4 уроков всего.
Чему я научусь в уроке «Управление приложениями с состоянием с помощью StatefulSets»?
Развёртывайте и управляйте приложениями с состоянием, например базами данных, с помощью StatefulSets, обеспечивая стабильные сетевые идентификаторы и постоянное хранилище. Ты практикуешь Docker & Kubernetes for Developers с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Docker & Kubernetes for Developers?
Предыдущий опыт не требуется. Docker & Kubernetes for Developers на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 2 из 4.
Сколько времени занимает урок «Управление приложениями с состоянием с помощью StatefulSets»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Docker & Kubernetes for Developers?
Да. Каждый урок Docker & Kubernetes for Developers включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Постоянные тома и запросы постоянных томов
- Управление приложениями с состоянием с помощью StatefulSets
- ConfigMaps и секреты для конфигурации
- Классы хранилищ и динамическое выделение