Keep a Kubernetes pod running

John McPeek
1 min readDec 1, 2023

--

Ok, you need a pod running so you can shell into it.

For example, you could use the pod as a bastion server; an easy way to access an environment with restricted access.

Normally people tell you to execute a sleep for infinity or some such like that. To my eye that is ugly and clumsy.

I suggest you try turning on stdin: true so the pod stays opens naturally. This causes the containers stdin to stay open waiting for somebody to attach to it (kucectl attach). While attach connects to a running process, we are going to use exec to run a command in that container, i.e. bash. So we can then execute commands from that container in that environment.

Save this as bastion.yaml

apiVersion: v1
kind: Pod
metadata:
labels:
run: bastion
name: bastion
spec:
containers:
- image: ubuntu:latest
name: tools
stdin: true
dnsPolicy: ClusterFirst
restartPolicy: Always

Then create the pod. In this case in the default namespace.

kubectl apply -f bastion.yaml

Once the pod starts you can shell into it with this:

kubectl exec -it bastion -- /bin/bash

In this case I used Ubuntu, but I usually use a tools image that gives me everything I need. Now you can get your job done and don’t need a separate service to SSH in.

See it in action here:

--

--

John McPeek

Sr Cloud Architect. AWS Certified Solutions Architect. Certified Kubernetes Application Developer (CKAD)