Is containerPort the port of a container in the port or the port itself?

1/1/2020

I saw that in Pod/Deployment YAML, there is the area of the container, where we declare our containers, with each container we can specify our ports (array) as containerPort.

If each Pod has multiple containers from multiple needs (web, database, etc...) and each container has a port, How can we select the targetPort in the service of that deployment? (Which container port do we select)

Is that service, a pod/deployment service or a container service? Because in the definition of a service, it's mentioned that it's a way to communicate the pods in a cluster.

Thanks

-- xgeek95
kubernetes

2 Answers

1/1/2020

You can have a single service targetting multiple ports.

apiVersion: v1
kind: Service
metadata: 
  name: myservice
spec: 
  ports:
  - name: web
    port: 80
    targetPort: 8080
  - name: database
    port: 3379
    targetPort: 3379
  selector: 
    name: mypod
-- Shashank V
Source: StackOverflow

1/1/2020

You can have a service that has multiple ports in the spec section to expose multiple ports and define target ports.The target ports has to match with the port exposed by containers in the pod.Also it's not necessary that port and target port has to be same.

spec:
  ports:
  - port: 3306
    name: mysql
    targetPort: 3306
  selector:
    name: mysql
    app: demo
  - port: 80
    name: web
    targetPort: 80
  selector:
    name: web
    app: demo

You should communicate with the containers via the service port and service will Loadbalance that request to one of the pods(if you have multiple replicas). Whenever pod comes or goes it will have a different IP. Using service you can avoid hardcoding the IP of the pod.

-- Arghya Sadhu
Source: StackOverflow