selecting containers within same Pod via Services

3/28/2018

I have two containers inside a Pod with label app=read-write. container-1 is reading on 7110 port and container-2 is listening on 7111. Now I need to connect with these containers via Services NodePorts. I create two separate services to assign NodePorts on each port (7110 and 7111).

---
apiVersion: v1
kind: Service
metadata:
  labels:
    app: read
    tier: service
  name: read
spec:
  ports:
  - port: 7110
    nodePort: 32000
    protocol: TCP
  type: NodePort
  selector:
    app: read
---
apiVersion: v1
kind: Service
metadata:
  labels:
    app: write
    tier: service
  name: write
spec:
  ports:
  - port: 7111
    nodePort: 32001
    protocol: TCP
  type: NodePort
  selector:
    app: write

but Services connect with Pods by matching label. So currently these two services will NOT connect with any pod because pod label is read-write and services are looking for any pod with label read or write. Is there any way in kubernetes where we can label containers inside a Pod ?

The only solution I have is to create single container per Pod and assign read and write label to each. But I really want to keep these two containers inside single pod.

-- Anum Sheraz
containers
kubectl
kubernetes
label

1 Answer

3/28/2018

The solution was rather simple, I've added two labels (with different keys) in both services, Instead of app:read and app:write, I've added read: read-service and write: write-service in my services. and in the Pod I've added both of these keys under label and selector;

Services readwrite.yml

---
apiVersion: v1
kind: Service
metadata:
  labels:
    read: read-service
    tier: service
  name: read-service
spec:
  ports:
  - port: 7110
    nodePort: 32000
    protocol: TCP
  type: NodePort
  selector:
    read: read-service
---
apiVersion: v1
kind: Service
metadata:
  labels:
    write: write-service
    tier: service
  name: write-service
spec:
  ports:
  - port: 7111
    nodePort: 32001
    protocol: TCP
  type: NodePort
  selector:
    write: write-service

deployment.yml

kind: Deployment
apiVersion: extensions/v1beta1
metadata:
  creationTimestamp: null
  labels:
    read: read-service
    write: write-service
    tier: service
  name: if11-read-write
spec:
  replicas: 1
  selector:
    matchLabels:
      read: read-service
      write: write-service
  template:
    metadata:
      labels:
        read: read-service
        write: write-service
        tier: service
    spec:
      containers:
      - name: read-container-name
        ...
      - name: write-container-name  
        ...

Now since both containers are under one Pod and having two labels, So read-service will look-up for a Pod with label read: read-service and assign a port 7110 and NodePort 32000. and write-service will look-up for a Pod with label write: write-service and assign a port 7111 and NodePort 32001.

-- Anum Sheraz
Source: StackOverflow