How to access the name of a pod?

Sometimes you need the name of a pod within a script (e.g. with kubectl exec). But since you normally want to use a deployment or replica set to manage your pod, the name of the pod might change and cannot be predicted.

There is an easy way to access the name of the pod via ‘kubectl’ with the help of labels. In this example we access the name of the pod described by the label label=value.

$kubectl get pod -l label=value -o jsonpath='{.items[0].metadata.name}'

For details on the jsonpath parameter can be found at https://kubernetes.io/docs/reference/kubectl/jsonpath/.

How to create an example kubernetes deployment?

Here is a simple example of how to create a kubernetes deployment out of a yaml file.

cat << EOF > client.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: client
  labels:
    app: client
spec:
  replicas: 1
  selector:
    matchLabels:
      app: client
  template:
    metadata:
      labels:
        app: client
    spec:
      containers:
      - name: client
        image: ubuntu:18.04
        command: ["sleep"]
        args: ["3600"]
      restartPolicy: Always
EOF

The file can then be applied with kubectl apply -f client.yaml.

To verify the pod being started, just run kubectl get pod -l app=client.

Accessing a port on a pod

With kubectl, you can just forward a specific port of some pod to your local machine. So you can test the pod. A simple example:

# Start a grafana pod
kubectl run grafana --image=grafana/grafana
POD=$(kubectl get pod -l run= grafana \ 
    -o jsonpath="{.items[0].metadata.name}")

# Forward port 3000
kubectl port-forward $POD 3000:3000 &

# Access port
curl -s http://localhost:3000/login | grep title