'how to specify service for 2nd container in container with two pods

I have defined a deployment with two containers:

selector:
    matchLabels:
      {{ $appLabelKey }}: {{ $appLabelValue }}
  template:
    metadata:
      annotations:
        ....
      labels:
        {{ $appLabelKey }}: {{ $appLabelValue }}
        app: james
spec:
      containers:
        - name: container1
          image: image1
          command: ['sh', '-c', 'while true; do echo Waiting tests execution finished; sleep 3600;done']
          imagePullPolicy: IfNotPresent
          env:

            
          volumeMounts:
          - mountPath: "/mnt/nfs"
            name: nfs-volume
          
          
        - name: james
          image: linagora/james-jpa-sample:3.4.0
          ports:
          - name: smtp-port
            containerPort: 25
          - name: imap-port
            containerPort: 143

I have a service for the Apache James that's in the second container:

apiVersion: v1
kind: Service
metadata:
  name: james-service
spec:
  selector:
    app: james
  ports:
  - port: 143
    targetPort: 143
    protocol: TCP
    name: imap-port
  - port: 25
    targetPort: 25
    protocol: TCP
    name: smtp-port
  type: LoadBalancer

However, the labels apply to both containers, not just the james container, is there a way to specify labels per container, rather than per deployment? The service sort of also applies to the other container, which is not working properly, its mount is there, but not working.



Solution 1:[1]

This is how you can do:

apiVersion: v1
kind: Service
metadata:
  name: container-1
spec:
  selector:
    app: web
  ports:
  - name: container-1
    port: 80
    targetPort: 80
---
apiVersion: v1
kind: Service
metadata:
  name: container-2
spec:
  selector:
    app: web
  ports:
  - name: container-2
    port: 80
    targetPort: 8080
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web
spec:
  replicas: 1
  selector:
    matchLabels:
      app: web
  template:
    metadata:
      labels:
        app: web
    spec:
      containers:
      - name: container-1
        image: traefik/whoami
        ports:
        - containerPort: 80
        env:
        - name: WHOAMI_NAME
          value: "container-1"
        
      - name: container-2
        image: traefik/whoami
        ports:
        - containerPort: 8080
        env:
        - name: WHOAMI_NAME
          value: "container-2"
        - name: WHOAMI_PORT_NUMBER
          value: "8080"
...

Apply the spec and run kubectl port-forward svc/container-1 8001:80 and kubectl port-forward svc/container-2 8002:80. To connect to container 1 curl localhost:8001, you can connect to another container in the same pod: curl localhost:8002.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 gohm'c