network-programmingservicekuberneteskubectlstatefulset

Kubernetes: Expose only single pod of StatefulSet


For for a StateFul set, I can access its pods via a headless service internally.

I think, it would make sense, to have an easy way to expose also single pods externally (since the pods usually have a state and therefore loadbalancing over them makes no sense).

So far, I found no straight forward way to do that. Even doing kubectl expose pod pod-1 --type NodePort gives me a service which balances over all pods. Is there a reason why this is like this or is there a nice way to access single pods.


Solution

  • You can expose a specific Pod in a StatefulSet externally by matching on the statefulset.kubernetes.io/pod-name label.

    For example, if your StatefulSet is named app and you want to expose port 80 from the first Pod as a Service:

    apiVersion: v1
    kind: Service
    metadata:
      name: app-0
    spec:
      type: LoadBalancer
      selector:
        statefulset.kubernetes.io/pod-name: app-0
      ports:
      - protocol: TCP
        port: 80
        targetPort: 80