Temp Curl pod for network testing

Add this to your .bashrc

alias k8_tmp_curl='kubectl run tmp-curl -it --rm --restart=Never --image=fedora:latest -- sh -c "dnf install -y curl && bash"'

kubectl Context Guard (Makefile pattern)

A small, portable pattern that pins every kubectl call in a project to one known context, so dev/PoC tooling can never accidentally hit a production cluster — even when your kubeconfig is full of prod contexts (e.g. Teleport).

The problem

If a Makefile runs bare kubectl apply ..., it targets whatever kubectl config current-context happens to be. Sign into a prod cluster (tsh kube login ...), forget to switch back, run make deploy, and you've just deployed into production. Calling kubectl config use-context inside the Makefile is worse: it silently mutates your global current context as a side effect of an unrelated command.

The pattern

Pin to a context with --context via one variable, and never mutate global state. Make every target use $(KUBECTL) instead of bare kubectl.

# Pin every kubectl call to a known-safe context. Override on the CLI if needed:
#   make deploy KUBE_CONTEXT=some-other-context
KUBE_CONTEXT ?= rancher-desktop
KUBECTL = kubectl --context $(KUBE_CONTEXT)

.PHONY: guard deploy clean
guard:
	@kubectl config get-contexts $(KUBE_CONTEXT) >/dev/null 2>&1 || { \
		echo "❌ kube-context '$(KUBE_CONTEXT)' not found."; \
		echo "   Available: kubectl config get-contexts -o name"; exit 1; }
	@$(KUBECTL) cluster-info >/dev/null 2>&1 || { \
		echo "❌ Cannot reach '$(KUBE_CONTEXT)'. Is the cluster up?"; exit 1; }
	@echo "✅ Targeting context: $(KUBE_CONTEXT)"

deploy: guard
	$(KUBECTL) apply -f manifests/

clean: guard
	$(KUBECTL) delete -f manifests/ --ignore-not-found

That's the whole pattern. Three rules:

  1. One variable (KUBECTL) carries --context; everything routes through it.
  2. Never call kubectl config use-context — pinning with --context leaves your interactive context untouched.
  3. guard runs first. Make destructive/apply targets depend on guard (deploy: guard) so they refuse to run against the wrong or an unreachable context.

Why --context instead of use-context

--context (this pattern)kubectl config use-context
ScopePer commandMutates global kubeconfig
Side effectsNoneChanges your interactive shell's context too
Safe alongside Teleport prod workYesNo — yanks you off whatever you were on
RevertingNothing to revertYou must remember to switch back

Overriding (escape hatch)

?= makes the default overridable without editing the file:

make deploy                              # uses rancher-desktop
make deploy KUBE_CONTEXT=kind-dev        # one-off override

For a different default per machine, set it in the environment:

export KUBE_CONTEXT=my-local-cluster

Reusing across projects

Copy the snippet into each project's Makefile and change the KUBE_CONTEXT default. To avoid duplication, keep it in a shared make/context-guard.mk and include it:

# make/context-guard.mk
KUBE_CONTEXT ?= rancher-desktop
KUBECTL = kubectl --context $(KUBE_CONTEXT)
guard:
	@kubectl config get-contexts $(KUBE_CONTEXT) >/dev/null 2>&1 || \
		{ echo "❌ context '$(KUBE_CONTEXT)' not found"; exit 1; }
	@$(KUBECTL) cluster-info >/dev/null 2>&1 || \
		{ echo "❌ cannot reach '$(KUBE_CONTEXT)'"; exit 1; }
# project Makefile
include make/context-guard.mk
deploy: guard
	$(KUBECTL) apply -f manifests/

Optional hardening

Singleton services in Kubernetes

For a service that should run as one pod and wait for its previous pod to terminate before replacement, use a StatefulSet with replicas: 1, a governing headless Service, and graceful application shutdown. This pattern also works without persistent volumes. StatefulSets provide stable pod identity and ordered lifecycle management. StatefulSet documentation.

For services that change shared external state, also enforce ownership in the application. A single Kubernetes pod identity alone cannot guarantee exclusive external writes under every failure condition.

Why one Deployment replica is insufficient

ConfigurationUpgrade behaviorOrdinary manual pod deletion
Deployment, one replica, default rolling updateCan start a replacement before the old pod stopsReplacement can overlap termination
Deployment, one replica, RecreateWaits for old pods to terminateReplacement can overlap termination
StatefulSet, one replicaReplaces the existing pod identity after terminationWaits before replacing the same pod identity

Recreate governs Deployment upgrades. Individual pod deletion is handled by the ReplicaSet, which can create a replacement while the old pod is still terminating. Kubernetes recommends considering a StatefulSet when an at-most guarantee is needed. Deployment documentation.

Manifest pattern

Replace the example image with the service's pinned image and set the ports to match the application. The application must implement graceful shutdown; adjust the grace period to its shutdown needs.

apiVersion: v1
kind: Service
metadata:
  name: singleton-service
spec:
  clusterIP: None
  selector:
    app: singleton-service
  ports:
    - name: http
      port: 8080
      targetPort: http
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: singleton-service
spec:
  serviceName: singleton-service
  replicas: 1
  podManagementPolicy: OrderedReady
  updateStrategy:
    type: RollingUpdate
  selector:
    matchLabels:
      app: singleton-service
  template:
    metadata:
      labels:
        app: singleton-service
    spec:
      terminationGracePeriodSeconds: 30
      containers:
        - name: application
          image: registry.example.com/team/singleton-service:1.0.0
          ports:
            - name: http
              containerPort: 8080

Keep the Service selector, StatefulSet selector, and pod labels aligned. serviceName references the headless Service. OrderedReady and RollingUpdate are explicit defaults here. With one replica, an update terminates the old pod and then creates its replacement; expect downtime. No extra pod is created to maintain availability. StatefulSet lifecycle and update behavior.

Application responsibilities

Handle termination signals and finish or cancel in-flight work within the configured grace period. Stop background tasks before releasing shared resources or application locks. Readiness controls traffic routing; it does not stop application code.

If concurrent access to a shared resource would cause corruption or duplicate effects, enforce exclusive access at the application or resource level as well. Locks and leader election can coordinate ownership, but loss of ownership must cause the old instance to stop. For strict protection against a stale instance, use fencing: the shared resource rejects operations from an obsolete owner.

The appropriate ownership mechanism depends on the application. StatefulSet lifecycle management alone does not enforce exclusive access to an external system.

Operational boundaries

Keep replicas fixed at one and avoid autoscaling this workload. A second StatefulSet, namespace, cluster, or standalone process can still target the same external resource; the Kubernetes identity guarantee is scoped to the managed pod identity.

Do not force-delete a stuck pod merely to restore availability. Force deletion removes its API identity without confirming that its process has stopped, allowing a replacement while the old process may still run. Confirm the old process is dead, or fence its access to shared resources, before permitting replacement. An unreachable node is not proof that its workload stopped. Kubernetes force-deletion guidance.

Waiting during an uncertain failure is an intentional availability tradeoff for a singleton. StatefulSet replacement does not eliminate the need for external ownership protection.

Migrating from a Deployment

Prevent the old Deployment and new StatefulSet from running together during the workload-kind change:

  1. Prevent deployment automation from restoring the old replica count during migration.
  2. Scale the existing Deployment to zero.
  3. Wait for its pods to finish terminating. Resolve unreachable-node cases before proceeding.
  4. Remove the old Deployment and apply the StatefulSet and headless Service manifests.
  5. Verify the replacement pod and application health before resuming normal automation.

For example, after selecting the correct cluster context:

kubectl -n <namespace> scale deployment/<old-name> --replicas=0
kubectl -n <namespace> wait --for=delete pod \
  -l '<selector-for-the-old-workload>' --timeout=120s
# Apply the new manifests only after the old processes are confirmed stopped.

Applying a Deployment-to-StatefulSet change in one operation does not establish this shutdown ordering. If the wait times out, investigate before creating the replacement.