kubernetes: Role of selector field in ReplicaSet definition

5/9/2019

Assuming we have a ReplicaSet definition file as follows:

apiVersion: apps/v1
kind: ReplicaSet
metadata: 
  name: my-deployment
  labels:
    tier: front-end
spec:
  template:
    metadata: 
      name: my-pod
      labels: 
        tier: front-end
    spec:
      containers:
        - name: my-container-1
          image: redis:latest
  replicas: 3
  selector:
    matchLabels:
      tier: front-end-2

How does kubernetes handle the fact that it should have 3 replicas of two different pods in terms of matched labels (i.e. tier:front-end and tier:front-end-2) ?

Should it make sure that e.g. the sum of these two differently labeled pods equals 3 ?

-- pkaramol
kubernetes
replicaset

1 Answer

5/9/2019

You would get an error that selector doesnt match pod label. here is the correct config

apiVersion: apps/v1
kind: ReplicaSet
metadata: 
  name: my-deployment
  labels:
    tier: front-end
spec:
  template:
    metadata: 
      name: my-pod
      labels: 
        tier: front-end
    spec:
      containers:
        - name: my-container-1
          image: redis:latest
  replicas: 3
  selector:
    matchLabels:
      tier: front-end

the pod label in pod spec should match with the selector. The number of replicas is 3. The replicaSet controller ensure that three pods are running at any point of time in the cluster. it uses the selector and the label from pod spec to identify the actual pods running and is matched against the desired count

-- P Ekambaram
Source: StackOverflow