E-NO
Kubernetes Lease local lab 7 Min Read

Kubernetes Lease Local Lab Setup with Practical Examples

calendar_today Published: 2026-11-21
update Last Updated: 2026-11-21
analytics SEO Efficiency: 97%
Technical guide illustration for Kubernetes Lease Local Lab Setup with Practical Examples.

Intro

Kubernetes Leases are a coordination primitive that let components claim and renew ownership of a shared resource for a limited time. The control plane uses them for leader election in components like kube-controller-manager and kube-scheduler, and the node lifecycle controller relies on them for node heartbeats. Despite their critical role, Leases are often overlooked until something goes wrong. Setting up a local lab gives you a safe, repeatable environment to understand how they work, test failure scenarios, and build operational confidence.

This guide walks through creating a practical Kubernetes Lease local lab. You will learn how to set up a minimal Kubernetes environment, create and inspect Lease objects, simulate holder crashes, and recover from expired Leases. By the end, you will have a solid foundation for troubleshooting Lease-related issues in production and for developing custom controllers that use Leases for leader election.

Version and Environment Inventory

Before you begin, establish the versions and topology of your lab. This ensures reproducibility and avoids surprises from API differences.

Prerequisites

  • Kubernetes cluster: A local single-node cluster is sufficient. We use kind (Kubernetes in Docker) for its simplicity, but minikube or k3s work equally well.
  • kubectl: The Kubernetes command-line tool, version matching or newer than the cluster.
  • A text editor for creating YAML manifests.
  • Basic understanding of Kubernetes API resources and kubectl.

Version Check

Run the following commands to verify your tools:

kubectl version --client
kind version

Expected output (example):

Client Version: v1.29.1
Kustomize Version: v5.0.4-0.20230601165947-6ce0bf390ce3
kind v0.22.0 go1.21.6 linux/amd64

Environment Topology

For this lab, we assume:

  • One Kubernetes cluster running locally.
  • The Lease API is available in the coordination.k8s.io/v1 group (stable since Kubernetes 1.14).
  • You have cluster-admin permissions in your local cluster (default in kind).

Check that the Lease API is available:

kubectl api-resources | grep leases

Expected output:

leases   coordination.k8s.io/v1   true   Lease

Quick check 1 of 2

Which control plane components use Leases for leader election to ensure only one instance actively runs in HA configurations?

Passage 1 states that Kubernetes uses Leases for leader election in control plane components like kube-controller-manager and kube-scheduler in HA configurations, where only one instance is active while others are standby.

Safe Configuration Path

Now we will set up a scoped environment for Lease experiments. To avoid interfering with system components, we will create a dedicated namespace and use a service account with restricted permissions.

Step 1: Create a Namespace and Service Account

Create a namespace called lease-lab:

kubectl create namespace lease-lab

Expected output:

namespace/lease-lab created

Create a service account lease-tester in that namespace:

kubectl create serviceaccount lease-tester -n lease-lab

Expected output:

serviceaccount/lease-tester created

Step 2: Define Minimal RBAC for Lease Operations

Create a Role that allows full control over Leases in the namespace. Save the following as lease-role.yaml:

apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  namespace: lease-lab
  name: lease-manager
rules:
- apiGroups: ["coordination.k8s.io"]
  resources: ["leases"]
  verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]

Apply the role:

kubectl apply -f lease-role.yaml

Expected output:

role.rbac.authorization.k8s.io/lease-manager created

Create a RoleBinding to bind the Role to the service account. Save as lease-rolebinding.yaml:

apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  namespace: lease-lab
  name: lease-tester-binding
subjects:
- kind: ServiceAccount
  name: lease-tester
  namespace: lease-lab
roleRef:
  kind: Role
  name: lease-manager
  apiGroup: rbac.authorization.k8s.io

Apply the binding:

kubectl apply -f lease-rolebinding.yaml

Expected output:

rolebinding.rbac.authorization.k8s.io/lease-tester-binding created

Step 3: Create a Sample Lease Object

Create a Lease named my-lease in the lease-lab namespace. A Lease requires a spec.holderIdentity and a spec.leaseDurationSeconds. Optionally, set spec.renewTime and spec.acquireTime.

Example manifest (lease.yaml):

apiVersion: coordination.k8s.io/v1
kind: Lease
metadata:
  name: my-lease
  namespace: lease-lab
spec:
  holderIdentity: "node-1"
  leaseDurationSeconds: 40
  acquireTime: "2023-10-01T12:00:00Z"
  renewTime: "2023-10-01T12:00:00Z"
  leaseTransitions: 0

Apply the manifest:

kubectl apply -f lease.yaml

Expected output:

lease.coordination.k8s.io/my-lease created

Verification and Diagnostics

Now verify that the Lease behaves as expected. We will inspect the object, simulate renewals, and check status fields.

Inspect the Lease Object

Use kubectl get to see the Lease in YAML form:

kubectl get lease my-lease -n lease-lab -o yaml

Expected output (truncated):

apiVersion: coordination.k8s.io/v1
kind: Lease
metadata:
  name: my-lease
  namespace: lease-lab
  ...
spec:
  holderIdentity: node-1
  leaseDurationSeconds: 40
  acquireTime: "2023-10-01T12:00:00Z"
  renewTime: "2023-10-01T12:00:00Z"
  leaseTransitions: 0

Check the holder identity:

kubectl get lease my-lease -n lease-lab -o jsonpath='{.spec.holderIdentity}'

Expected output:

node-1

Simulate a Renewal

A holder renews a Lease by updating the renewTime and optionally bumping leaseTransitions. Use kubectl patch to simulate a renewal:

kubectl patch lease my-lease -n lease-lab --type merge -p '{"spec":{"renewTime":"2023-10-01T12:00:20Z"}}'

Expected output:

lease.coordination.k8s.io/my-lease patched

View the updated renewTime:

kubectl get lease my-lease -n lease-lab -o jsonpath='{.spec.renewTime}'

Expected output:

2023-10-01T12:00:20Z

Watch Lease Changes

To observe changes in real time, use kubectl get --watch in a separate terminal:

kubectl get lease my-lease -n lease-lab --watch

In another terminal, patch the Lease again and you will see the updated line appear.

Failure Modes and Recovery

Understanding failure modes is critical. We will simulate a holder crash, observe Lease expiry, and practice recovery by assigning a new holder.

Simulate a Holder Crash

Stop renewing the Lease. After leaseDurationSeconds (40 seconds in our example), the Lease is considered expired by other components, but the object remains with stale data. In a real system, a new candidate would attempt to acquire it.

Simulate a New Holder Acquisition

To simulate a new holder taking over, update the holderIdentity, set acquireTime to the current time, renewTime to the current time, and increment leaseTransitions by 1.

First, get the current time in RFC3339 format:

NOW=$(date -u +"%Y-%m-%dT%H:%M:%SZ")

Then patch the Lease:

kubectl patch lease my-lease -n lease-lab --type merge -p "{\"spec\":{\"holderIdentity\":\"node-2\",\"acquireTime\":\"$NOW\",\"renewTime\":\"$NOW\",\"leaseTransitions\":1}}"

Expected output:

lease.coordination.k8s.io/my-lease patched

Verify the transition:

kubectl get lease my-lease -n lease-lab -o yaml

Look for holderIdentity: node-2 and leaseTransitions: 1.

Rollback and Recovery

If you need to roll back a faulty update, you can use the Lease's managedFields or maintain a backup of the YAML. For quick recovery, save a copy before making changes:

kubectl get lease my-lease -n lease-lab -o yaml > lease-backup.yaml

To restore from backup:

kubectl apply -f lease-backup.yaml

Note: Applying may not overwrite all fields if resourceVersion conflicts occur; delete and recreate if necessary.

Quick check 2 of 2

Based on the naming guidance for custom workload Leases, if a component is named 'Example Foo', what Lease name is recommended?

Passage 2 recommends naming a Lease obviously linked to the product or component, giving the example that a component named Example Foo should use a Lease named example-foo.

Common Pitfalls and How to Avoid Them

Working with Leases can lead to subtle mistakes. Here are the most common pitfalls, why they happen, and how to avoid or recover from them.

Using the Wrong API Group or Version

Why it happens: Older documentation or examples may reference coordination.k8s.io/v1beta1. That version was deprecated and removed in Kubernetes 1.22.

How to avoid: Always use coordination.k8s.io/v1. Verify with kubectl api-resources | grep leases before writing manifests.

Recovery: If you applied a v1beta1 Lease and the API is gone, delete the old object and recreate it as v1.

Not Setting a Realistic leaseDurationSeconds

Why it happens: If the duration is too short, the holder may lose the Lease before it can renew, causing flapping and unnecessary transitions. If too long, failure detection slows down.

How to avoid: Choose a duration based on your renew loop interval. A common pattern is to set leaseDurationSeconds to at least 2-3 times the renew interval. For manual testing, 40 seconds works well.

Recovery: Patch the Lease with a longer duration:

kubectl patch lease my-lease -n lease-lab --type merge -p '{"spec":{"leaseDurationSeconds":120}}'

Ignoring leaseTransitions

Why it happens: New holders forget to increment leaseTransitions. Observers use this field to detect that a new holder took over. If it stays at 0, it may look like the same holder is still active.

How to avoid: Always increment leaseTransitions when changing holderIdentity. If you use client libraries, they should do this automatically, but manual patches must include it.

Recovery: Patch the Lease to set the correct transition count:

kubectl patch lease my-lease -n lease-lab --type merge -p '{"spec":{"leaseTransitions":2}}'

Using Static Times in Manifests

Why it happens: Copying an example with hardcoded times like 2023-10-01T12:00:00Z leads to confusion when the current time differs. The Lease may appear expired immediately.

How to avoid: Always use the current time when creating or updating a Lease. In shell, use date -u +"%Y-%m-%dT%H:%M:%SZ". In client code, use metav1.Now() or time.Now().

Recovery: Patch the Lease with fresh times as shown earlier.

Forgetting to Clean Up Namespaces

Why it happens: Leases are lightweight, so many developers leave test Leases behind, cluttering the cluster and potentially confusing future experiments.

How to avoid: Always delete the namespace at the end of a lab session: kubectl delete namespace lease-lab.

Recovery: If you forget, simply delete the namespace later; it removes all resources inside it.

Operations Checklist

Use this checklist for safe and repeatable Lease operations in your lab. Assign a single accountable owner for each step in a team setting; for solo work, you are the owner. Revisit this checklist monthly or whenever you modify your Lease handling code.

StepDescriptionCommand / CheckExpected ResultOwnerReview Frequency
1Verify environmentkubectl version --client and kind versionVersions match requirementsPlatform Engineer (e.g., Alex Chen)Monthly
2Create namespacekubectl create namespace lease-labNamespace createdPlatform EngineerPer lab session
3Create RBACApply role and rolebindingService account has minimal permissionsSecurity Lead (e.g., Maria Lopez)Quarterly
4Create a LeaseApply lease manifestLease object existsDeveloper (e.g., Priya Shah)Per lab session
5Inspect Leasekubectl get lease my-lease -n lease-lab -o yamlHolder identity setDeveloperPer lab session
6Test renewalPatch renewTimerenewTime updatesDeveloperPer lab session
7Simulate holder changePatch holderIdentity and transitionsNew holder recordedDeveloperPer lab session
8Backup before changeskubectl get lease ... -o yaml > backup.yamlBackup file createdDeveloperPer lab session
9Restore if neededApply backup manifestOriginal state restoredDeveloperPer lab session
10Clean upkubectl delete namespace lease-labAll resources removedPlatform EngineerPer lab session

Conclusion

You now have a functional Kubernetes Lease local lab. You learned how to set up a scoped environment, create and manipulate Lease objects, verify their behavior, simulate failures, and recover. This lab provides a safe playground for exploring Lease semantics, testing leader election patterns, and developing custom controllers that rely on Leases.

Next steps:

  • Experiment with Lease preferredHolder and strategy fields.
  • Observe how kube-controller-manager uses Leases for leader election by inspecting the kube-system namespace.
  • Build a small application that uses the Kubernetes client library to acquire and renew a Lease.

Remember, the first useful pilot should be narrow and measurable. This lab is a perfect foundation for deeper learning and safe experimentation before touching production.

Related Research

Article Quality Score

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