Kubernetes Service selector to a container

11/18/2019

I have two containers in one pod and the Kubernetes services have a selector to the pod.

Container 1 is a UI, exposing the port 8080. Container 2 is a service to sync with Git.

The issue I have is when the "Container 2" dies (because the Git is down for example) the Kubernetes Service removes the pod from the pool and the service is not routing traffic to the pod.

How can I set in the Kubernetes Service the selector to the container and not to the pod, or some workaround ?

---
apiVersion: v1
kind: Service
metadata:
  name: myapp
  namespace: default
spec:
  selector:
    app: myapp
  ports:
    - port: 80
      targetPort: 8080
      protocol: TCP

---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: myapp
  namespace: default
  labels:
    app: myapp
spec:
  replicas: 1
  selector:
    matchLabels:
      app: myapp
  template:
    metadata:
      labels:
        app: myapp
    spec:
      containers:
        - name: git
          image: git:1.0

        - name: ui
          image: ui:1.0
          ports:
            - containerPort: 8080

Thanks!

-- mrbit01
kubernetes
service

2 Answers

11/18/2019

How can I set in the Kubernetes Service the selector to the container and not to the pod, or some workaround ?

No. You cannot. Any workaround (if any) will be a kind of k8s anti pattern, just because the deployment was not designed for that. More info:

kubectl explain deployment.spec.template.metadata
kubectl explain deployment.spec.template.spec.containers
-- Konstantin Vustin
Source: StackOverflow

11/18/2019

Although POD can run more than one containers, The failure of those containers are managed together by Kubernetes. You can refer here.

When you have a pod running two containers, ideally the second container must be a helper container - similiar to a SideCar implementation, where it just does update or read of data to be used by the main container.

Pod life cycle doc from kubernetes clearly explains the same.

Pod is running and has two Containers.
Container 1 exits with failure:

Log failure event.
If restartPolicy is: Always:
Restart Container;
Pod phase stays Running.
If restartPolicy is: OnFailure:
Restart Container;
Pod phase stays Running.
If restartPolicy is: Never:
Do not restart Container;
Pod phase stays Running.

If Container 1 is not running, and Container 2 exits: Log failure event.

If restartPolicy is: Always:
Restart Container;
Pod phase stays Running.
If restartPolicy is: OnFailure:
Restart Container;
Pod phase stays Running.
If restartPolicy is: Never:
Pod phase becomes Failed.

-- Srini M
Source: StackOverflow