<p>I have a StatefulSet with 3 pods. The first is assigned to the master role, the rest have a read replica role.</p>
<pre><code>redis-0 (master)
redis-1 (replica)
redis-2 (replica)
</code></pre>
<p>How can I create a Kubernetes Service that matches only the pods <code>redis-1</code> and <code>redis-2</code>? Basically I want to service that points only to the pods acting as replicas?</p>
<p>Logically what I want is to select every pod in the STS <em>except</em> the first. In pseudocode:</p>
<pre><code>selector: app=redis-sts &amp;&amp; statefulset.kubernetes.io/pod-name!=redis-0
</code></pre>
<p>Alternatively, selecting all the relevant pods could be viable. Again in psuedocode:</p>
<pre><code>selector: statefulset.kubernetes.io/pod-name=redis-1 || statefulset.kubernetes.io/pod-name=redis-2
</code></pre>
<p>Here is the relevant YAML with the selectors &amp; service defined. <a href="https://github.com/WilliamDenniss/kubernetes-quickly/blob/master/Chapter09/9.2.2_StatefulSet_Redis_Replicated/redis-statefulset.yaml" rel="noreferrer">Full YAML</a>.</p>
<pre><code>apiVersion: v1
kind: Service
metadata:
  name: redis-service
spec:
  ports:
  - port: 6379
  clusterIP: None
  selector:
    app: redis-sts
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: redis
spec:
  selector:
    matchLabels:
      app: redis-sts
  serviceName: redis-service
  replicas: 3
  template:
    metadata:
      labels:
        app: redis-sts
    spec:
# ...
</code></pre>

William Denniss
<p>You may use <a href="https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/#pod-name-label" rel="noreferrer">pod name labels</a> of your redis statefulset to create the  service to access a particular read replica pod.</p>
<pre><code>apiVersion: v1
kind: Service
metadata:
  name: redis-1
spec:
  type: LoadBalancer
  externalTrafficPolicy: Local
  selector:
    statefulset.kubernetes.io/pod-name: redis-1
  ports:
  - protocol: TCP
    port: 6379
    targetPort: 6379
</code></pre>
<p>And then use the service name for the pod to access the specific pods.</p>
<p><strong>externalTrafficPolicy: Local</strong> will only proxy the traffic to the node that has the instance of your pod.</p>
