Changing pod's labels on the fly

2/13/2015

I wonder if it is possible to change labels of pods on the fly so services route requests to those pods based on new labels.

For example I have two services A and B. Then I have 10 pods, where 5 have label type = A (matches service A) and the other 5 have label type = B (matches service B). At some point I want to change labels on pods to achieve a configuration of 2 with label type = A and 8 with label type = B.

I want to know if I can just change the labels and services will be updated accordingly without having to stop and start new pods with different labels.

-- dgaviola
kubernetes

2 Answers

2/13/2015

You can change the labels on individual pods using the kubectl label command, documented here.

Changing the label of a running pod should not cause it to be restarted, and services will automatically detect and handle label changes.

So in other words, yes you can :)

-- Alex Robinson
Source: StackOverflow

1/31/2019

The steps are As follows:

  1. Create two deployments with a label for each and mention number of pods you wish to have In them.

Deploytask1.yaml

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: task1deploy
spec:
  replicas: 5
  template:
    metadata:
      labels:
        app: task1deploy
    spec:
      containers:
      - name: nodetask1

Deploy2task1.yaml

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: task1deploy2
spec:
  replicas: 5
  template:
    metadata:
      labels:
        app: task1deploy2
    spec:
      containers:
      - name: node2task1
        image: nginx
        ports:
        - containerPort: 80

2.Create two services :

kubectl expose deployment task1deploy --namespace=shifali --type=LoadBalancer --name=my-service
kubectl expose deployment task1deploy2 --namespace=shifali --type=LoadBalancer --name=my-service2

3.When you describe these services you will find 5 endpoints to each(that is the pods):

kubectl describe service my-service  --namespace=shifali

Name: task1deploy

Endpoints: 10.32.0.12:80,10.32.0.7:80,10.32.0.8:80 + 3 more...

And similarly for service2

6.Now remove the label of pod new11 and add label “app=task1deploy2”

kubectl label pods new11-68dfd7d4c8-64xhq  --namespace=shifali app-  
kubectl label pods new11-68dfd7d4c8-64xhq "app=task1deploy2" --namespace=Shifali

Now the services will show variation in the number of target ports (my_service=5 and my_service2=7)

kubectl describe service my-service --namespace=Shifali

Endpoints:10.32.0.7:80,10.32.0.8:80,10.32.1.7:80 + 2 more..

kubectl describe service my-service2 --namespace=Shifali

Name: my-service2 Endpoints: 10.32.0.10:80,10.32.0.12:80,10.32.0.9:80 + 4 more...

-- Shifali Srivastava
Source: StackOverflow