E-NO
Kubernetes StatefulSet security 12 Min Read

Kubernetes StatefulSet Security Hardening with Practical Examples

calendar_today Published: 2026-11-29
update Last Updated: 2026-11-29
analytics SEO Efficiency: 100%
Technical guide illustration for Kubernetes StatefulSet Security Hardening with Practical Examples.

Intro

StatefulSets are the Kubernetes workload of choice for applications that need stable identities, persistent storage, and ordered deployment. Databases, message queues, and distributed systems rely on these guarantees. However, StatefulSets also inherit every security challenge of pods plus additional risks from persistent data and stable network identities. A compromised StatefulSet can leak sensitive data, allow lateral movement, or disrupt critical services.

This guide provides practical security hardening for StatefulSets. We will cover access control, secrets management, pod security, network policies, storage protection, and operational verification. Each section includes concrete commands and configuration examples you can apply to your cluster. The focus is on actionable steps that reduce attack surface without breaking application functionality.

Security is not a one-time task but a continuous practice. This guide helps you build a hardening checklist suitable for production environments. By following these steps, you can protect stateful workloads against common threats and meet compliance requirements. The examples use Kubernetes 1.28+ and assume a basic understanding of StatefulSets.

Version and Environment Inventory

Before hardening, document your Kubernetes version, storage classes, and StatefulSet configurations. Knowing the exact environment helps you choose the right security features and avoid compatibility issues.

Cluster baseline

Run the following commands to gather version and node information:

kubectl version --short
kubectl get nodes -o wide
kubectl get storageclass

Expected output resembles:

Client Version: v1.28.3
Server Version: v1.28.3
NAME STATUS ROLES AGE VERSION INTERNAL-IP EXTERNAL-IP OS-IMAGE KERNEL-VERSION CONTAINER-RUNTIME
node-1 Ready control-plane 10d v1.28.3 192.168.1.10 <none> Ubuntu 22.04.3 LTS 5.15.0-91-generic containerd://1.7.2
node-2 Ready <none> 10d v1.28.3 192.168.1.11 <none> Ubuntu 22.04.3 LTS 5.15.0-91-generic containerd://1.7.2
NAME PROVISIONER RECLAIMPOLICY VOLUMEBINDINGMODE ALLOWVOLUMEEXPANSION AGE
standard (default) rancher.io/local-path Delete WaitForFirstConsumer false 10d

Note the storage class reclaim policy. For stateful data, consider using a storage class with Retain policy to prevent accidental data loss.

Existing StatefulSet review

List existing StatefulSets and inspect their security-relevant fields:

kubectl get statefulsets --all-namespaces
kubectl describe statefulset <name> -n <namespace>

Pay attention to:

  • serviceAccountName: which service account the pods use
  • securityContext: pod and container level settings
  • volumeClaimTemplates: PVCs and storage classes
  • podManagementPolicy: OrderedReady (default) or Parallel

Also check the Kubernetes version for enabled admission controllers and feature gates. Pod Security Admission (PSA) and NodeRestriction are important for hardening. To see enabled admission plugins (if you have access to the API server), use:

kubectl get --raw /metrics | grep apiserver_admission_controller_admission_duration_seconds | head

For managed clusters, check the provider documentation.

Quick check 1 of 2

Which of the following is NOT a characteristic that makes StatefulSets valuable for certain applications?

The passage lists stable network identifiers, persistent storage, ordered deployment/scaling, and ordered rolling updates as valuable features of StatefulSets. Automatic horizontal scaling based on CPU is not mentioned.

Safe Configuration Path

Implement hardening in small, reviewable steps. Start with the least disruptive changes: service accounts, security contexts, and secrets. Then apply network policies and pod security standards. Each step includes a verification command.

Step 1: Dedicated service account with least privilege

Each StatefulSet should use its own service account rather than the default. Create a service account and assign only the roles it needs via RBAC.

Create a service account:

kubectl create serviceaccount myapp-sa -n mynamespace

If your application does not need Kubernetes API access, do not mount the default token. In the StatefulSet pod spec, set automountServiceAccountToken: false:

apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: myapp
  namespace: mynamespace
spec:
  serviceName: myapp
  replicas: 3
  selector:
    matchLabels:
      app: myapp
  template:
    metadata:
      labels:
        app: myapp
    spec:
      serviceAccountName: myapp-sa
      automountServiceAccountToken: false
      containers:
      - name: app
        image: myapp:1.0

Apply and confirm:

kubectl apply -f statefulset.yaml
kubectl get pod -n mynamespace -l app=myapp -o jsonpath='{.items[0].spec.serviceAccountName}{"\n"}'

Expected output: myapp-sa

If your application needs API access, grant specific permissions using Roles and RoleBindings. For example, read-only access to ConfigMaps in the same namespace:

apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  namespace: mynamespace
  name: configmap-reader
rules:
- apiGroups: [""]
  resources: ["configmaps"]
  verbs: ["get", "list", "watch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  namespace: mynamespace
  name: read-configmaps
subjects:
- kind: ServiceAccount
  name: myapp-sa
  namespace: mynamespace
roleRef:
  kind: Role
  name: configmap-reader
  apiGroup: rbac.authorization.k8s.io

Apply the RBAC files:

kubectl apply -f role.yaml -f rolebinding.yaml

Step 2: Pod and container security contexts

Set security contexts to enforce least privilege at runtime. Key settings:

  • runAsNonRoot: true
  • runAsUser: <non-zero uid>
  • allowPrivilegeEscalation: false
  • capabilities: drop: ["ALL"]
  • seccompProfile: RuntimeDefault

Example pod spec snippet:

spec:
  securityContext:
    runAsNonRoot: true
    runAsUser: 1000
    runAsGroup: 2000
    fsGroup: 2000
    seccompProfile:
      type: RuntimeDefault
  containers:
  - name: app
    image: myapp:1.0
    securityContext:
      allowPrivilegeEscalation: false
      capabilities:
        drop: ["ALL"]
      readOnlyRootFilesystem: true

Note: readOnlyRootFilesystem may require writable volumes for temporary files. Add emptyDir volumes if needed.

Apply and verify:

kubectl apply -f statefulset.yaml
kubectl get pod -n mynamespace -l app=myapp -o jsonpath='{.items[0].spec.containers[0].securityContext}{"\n"}'

Expected output:

{"allowPrivilegeEscalation":false,"capabilities":{"drop":["ALL"]},"readOnlyRootFilesystem":true}

Step 3: Secret management

Avoid environment variables for secrets; prefer mounted volumes from Kubernetes Secrets. Enable encryption at rest for Secrets in etcd (requires cluster admin). Use tools like Sealed Secrets or External Secrets Operator for GitOps workflows.

Create a secret:

kubectl create secret generic db-credentials -n mynamespace --from-literal=username=appuser --from-literal=password='S3cureP@ss'

Mount the secret as a volume in the StatefulSet:

spec:
  template:
    spec:
      containers:
      - name: app
        image: myapp:1.0
        volumeMounts:
        - name: db-secret
          mountPath: /etc/secrets/db
          readOnly: true
      volumes:
      - name: db-secret
        secret:
          secretName: db-credentials

Verify the secret is mounted:

kubectl exec -n mynamespace myapp-0 -- ls /etc/secrets/db

Expected output:

password  username

Step 4: Network policies

StatefulSets often need stable network identities. Use NetworkPolicies to restrict traffic to only necessary sources and ports. The following policy allows ingress to pods with label app: myapp from pods with label access: allowed on TCP 5432 (PostgreSQL example).

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: myapp-network-policy
  namespace: mynamespace
spec:
  podSelector:
    matchLabels:
      app: myapp
  policyTypes:
  - Ingress
  ingress:
  - from:
    - podSelector:
        matchLabels:
          access: allowed
    ports:
    - protocol: TCP
      port: 5432

Apply:

kubectl apply -f networkpolicy.yaml

Test connectivity from an allowed pod and a denied pod. Allowed pod should succeed, denied pod should timeout.

Step 5: Pod Security Standards

Enforce baseline or restricted Pod Security Standards at namespace level. For new clusters, use PSA labels. Example label for baseline:

kubectl label namespace mynamespace pod-security.kubernetes.io/enforce=baseline

For existing StatefulSets, ensure they comply. If not, adjust security contexts as needed. You can also use a validating webhook like Kyverno or OPA Gatekeeper for more granular policies.

Apply label and check warnings:

kubectl label namespace mynamespace pod-security.kubernetes.io/enforce=baseline --overwrite
kubectl get events -n mynamespace --field-selector type=Warning

No warnings indicate compliance.

Step 6: Storage hardening

Persistent volume claims should be protected. Ensure PVCs use ReadWriteOnce (default) unless shared storage is required. Use storage classes with volumeBindingMode: WaitForFirstConsumer to avoid premature node binding. Set reclaim policy to Retain for critical data to prevent deletion on PVC deletion.

Example PVC template inside StatefulSet:

volumeClaimTemplates:
- metadata:
    name: data
  spec:
    accessModes: [ "ReadWriteOnce" ]
    storageClassName: standard
    resources:
      requests:
        storage: 10Gi

Check existing PVCs:

kubectl get pvc -n mynamespace

Expected output:

NAME           STATUS   VOLUME                                     CAPACITY   ACCESS MODES   STORAGECLASS   AGE
data-myapp-0   Bound    pvc-1234abcd-5678-efgh-ijkl-1234567890ab   10Gi       RWO            standard       5d
data-myapp-1   Bound    pvc-5678efgh-...                          10Gi       RWO            standard       5d

Step 7: Enable audit logging

Kubernetes audit logs record API requests. Configure audit policy to log events for StatefulSet resources. This helps detect unauthorized access. For managed clusters, enable audit logs in the cloud provider console. For self-managed, set --audit-policy-file and --audit-log-path on the API server.

Example audit policy rule to log StatefulSet changes:

apiVersion: audit.k8s.io/v1
kind: Policy
rules:
- level: Metadata
  resources:
  - group: apps
    resources: ["statefulsets"]

Then restart API server with the policy file. Verify logs are written to the specified path.

Verification and Diagnostics

After applying hardening configurations, verify that everything works as expected. Use the following checks.

Check pod security context

kubectl get pod -n mynamespace -l app=myapp -o json | jq '.items[0].spec | {serviceAccountName, securityContext: .securityContext, automountServiceAccountToken}'

Expected output:

{
  "serviceAccountName": "myapp-sa",
  "securityContext": {
    "runAsNonRoot": true,
    "runAsUser": 1000,
    "runAsGroup": 2000,
    "fsGroup": 2000,
    "seccompProfile": {
      "type": "RuntimeDefault"
    }
  },
  "automountServiceAccountToken": false
}

If automountServiceAccountToken is false, the token should not be mounted. Verify:

kubectl exec -n mynamespace myapp-0 -- ls /var/run/secrets/kubernetes.io/serviceaccount

Expected output: error or no such directory.

Check network policy enforcement

Test connectivity from a pod that should be allowed and one that should be denied.

Create a temporary pod with label access: allowed:

kubectl run test-allowed --image=busybox -n mynamespace --labels=access=allowed -- sleep 3600

From that pod, try to connect to the StatefulSet service on port 5432:

kubectl exec -n mynamespace test-allowed -- nc -zv myapp-0.myapp.mynamespace.svc.cluster.local 5432

Expected output: Connection to myapp-0.myapp.mynamespace.svc.cluster.local 5432 port [tcp/postgresql] succeeded!

Create a pod without the label:

kubectl run test-denied --image=busybox -n mynamespace -- sleep 3600

Test:

kubectl exec -n mynamespace test-denied -- nc -zv myapp-0.myapp.mynamespace.svc.cluster.local 5432

Expected output: timeout (no connection)

Clean up test pods:

kubectl delete pod test-allowed test-denied -n mynamespace

Check PSA enforcement

If PSA baseline is enforced, attempting to run a privileged pod should be rejected. Try:

kubectl run privileged-test --image=busybox -n mynamespace --overrides='{"spec":{"containers":[{"name":"privileged-test","image":"busybox","securityContext":{"privileged":true}}]}}'

Expected output: error message from admission webhook denying the pod.

Audit log inspection

If audit logging is enabled, look for StatefulSet-related events. Use your log aggregation tool or grep on the audit log file:

grep "statefulsets" /var/log/kubernetes/audit/audit.log | tail

Expected output: lines containing "resource":"statefulsets" with metadata.

Quick check 2 of 2

What does the 'stable' in stable network identity and stable storage mean in the context of StatefulSets?

The passage states: 'In the above, stable is synonymous with persistence across Pod (re)scheduling.'

Common Pitfalls and How to Avoid Them

Even experienced teams encounter issues when hardening StatefulSets. Here are the most frequent mistakes, why they happen, and how to prevent or recover from them.

Pitfall 1: Overly restrictive security contexts break applications

Why it happens: Setting runAsNonRoot: true or readOnlyRootFilesystem: true without testing can cause the container to fail to start or crash because the application expects to run as root or write to its root filesystem.

How to avoid: Test security contexts in a staging environment with the same container image. Check the image's Dockerfile or entrypoint to determine the intended user and filesystem writes. Use kubectl logs to diagnose failures.

Recovery: Temporarily remove the restrictive field, fix the application or add writable volume mounts, then reapply.

Pitfall 2: Network policies block required traffic

Why it happens: A NetworkPolicy with a narrow podSelector or missing egress rules can block legitimate traffic, such as DNS lookups or connections to other services.

How to avoid: Start with a policy that allows necessary egress (e.g., DNS on port 53) and then tighten ingress rules incrementally. Test connectivity from all relevant pods.

Recovery: Delete or update the NetworkPolicy to add the missing selectors or ports. Reapply and verify.

Pitfall 3: Using default service account with escalated permissions

Why it happens: Teams often leave the default service account, which may have broader permissions than needed, especially if cluster roles were previously bound to it.

How to avoid: Always create a dedicated service account for each StatefulSet and grant only the required RBAC permissions. Set automountServiceAccountToken: false if the pod does not need API access.

Recovery: Switch to a new service account with proper RBAC and restart the StatefulSet pods.

Pitfall 4: Secrets exposed via environment variables

Why it happens: Developers often pass secrets as environment variables because it is convenient, but env vars can be logged or exposed via the API.

How to avoid: Mount secrets as files in a volume and ensure they are read-only. Use a secrets management tool like External Secrets Operator or Sealed Secrets for GitOps.

Recovery: Refactor the application to read secrets from files, update the StatefulSet spec, and rotate the secrets.

Pitfall 5: Storage reclaim policy causes data loss

Why it happens: The default storage class often has Delete reclaim policy. If a PVC is deleted accidentally, the underlying volume and all data are lost.

How to avoid: Use a storage class with Retain policy for stateful workloads. Regularly back up persistent volumes.

Recovery: If data is lost, restore from backup. If the volume still exists but is in Released state, you can manually recover it by creating a new PV and PVC referencing it.

Pitfall 6: Ignoring Pod Security Standards warnings

Why it happens: Teams apply PSA labels without checking compliance, leading to pods being rejected at creation time or warnings being ignored.

How to avoid: Gradually enforce PSA by starting with warn and audit modes before enforce. Review existing workloads and fix security contexts.

Recovery: Remove or adjust the PSA label temporarily, fix the pod specs, then reapply the label.

Operations Checklist

Use this checklist as part of your regular security review and when deploying new StatefulSets. Assign a single owner for each item and set a recurring review cadence.

AreaCheckOwner (example)Review FrequencyCommand or Action
Service AccountDedicated SA, token not automounted if unnecessarySecurity Engineer (e.g., Priya Shah)Monthlykubectl get pod -o json inspect
RBACLeast privilege roles for SAPlatform Admin (e.g., Carlos Mendes)Monthlykubectl auth can-i --as=system:serviceaccount:mynamespace:myapp-sa list pods
Security ContextrunAsNonRoot, drop caps, seccompApplication Owner (e.g., David Chen)Weeklykubectl get pod -o jsonpath='{.spec.containers[0].securityContext}'
SecretsMounted as volumes, not env vars; encryption at restSecurity EngineerMonthlykubectl get secret and inspect pod spec
Network PoliciesIngress/Egress restricted to necessary endpointsPlatform AdminMonthlykubectl get networkpolicy
Pod SecurityNamespace PSA label set to baseline/restrictedPlatform AdminMonthlykubectl get ns mynamespace --show-labels
StoragePVC access modes, reclaim policy, backupsApplication OwnerQuarterlykubectl get pvc and kubectl get storageclass
AuditingAudit logs enabled for StatefulSet eventsSecurity EngineerMonthlyCheck API server flags or cloud provider
UpdatesStatefulSet image updates use rolling update with health checksApplication OwnerWeeklykubectl get statefulset -o yaml inspect updateStrategy

Run these checks periodically and after any configuration change. The owner is responsible for ensuring the check is performed and for remediating any failures.

Conclusion

Securing StatefulSets requires a layered approach: least privilege service accounts, runtime security contexts, secret management, network restrictions, and storage protection. This guide provided practical examples and verification steps for each layer. By implementing these hardening measures, you reduce the risk of data breaches and service disruption.

Security is an ongoing process. Regularly review your StatefulSet configurations against the operations checklist, stay updated with Kubernetes security advisories, and test changes in a staging environment before production. The steps in this guide are designed to be incremental, allowing you to adopt them without a full redesign. Start with the most impactful changes: service accounts and security contexts, then add network policies and PSA. Your stateful workloads will be better protected against common threats.

For further reading, consult the official Kubernetes documentation on StatefulSets, Pod Security Standards, and Network Policies. Remember to validate all changes with your team and maintain backups of critical data.

Related Research

Article Quality Score

Reader usefulness 100%
  • check_circle Reader-ready guide
  • check_circle Practical examples included
  • check_circle Clean SEO article URL