Search code examples
kuberneteskubernetes-statefulset

How to select multiple pod for a service in Kubernetes


I want to link services to specific pod by using StatefulSets in Kubernetes as below.

  • service_1 links to web-0, web-1 pod
  • service_2 links to web-2, web-3 pod

I know there is a label to select specific pod

"statefulset.kubernetes.io/pod-name: web-01"

but this label seems only select one pod. Is there a way to select multiple pod?


Solution

  • If you need to point services into a portion of pods in a StatefulSet, the best practice is to create multiple StatefulSets, or use Canary Deployments with StatefulSets

    If you need to know how to point a service into a StatefulSet, there is three options:

    1. Create a headless service for the StatefulSet.

    2. Use the service name as the hostname in the StatefulSet pod specification.

    apiVersion: apps/v1
    kind: StatefulSet
    metadata:
      name: my-statefulset
    spec:
      serviceName: my-statefulset
      replicas: 3
      selector:
        matchLabels:
          app: my-statefulset
      template:
        metadata:
          labels:
            app: my-statefulset
        spec:
          hostname: my-statefulset
          subdomain: my-namespace.svc.cluster.local
          containers:
          - name: my-container
            image: my-image
            command: ["/bin/sh"]
            args: ["-c", "while true; do sleep 3600; done"]
    
    1. Use environment variables or DNS resolution to connect to the service from within the pod.

    To point a service to multiple pod names, there is no possible way, According to documentation:

    Caution: For both equality-based and set-based conditions there is no logical OR (||) operator. Ensure your filter statements are structured accordingly