Why do we need a port/containerPort in a Kuberntes deployment/container definition?

7/25/2019

When I define e.g. a deployment in kubernetes there is a section with a list of containers and each of them contains an array of ports, e.g.:

apiVersion: apps/v1
kind: Deployment
spec:
  template:
    spec:
      containers:
      - name: my-nginx
        image: nginx
        ports:
        - containerPort: 80

Now the documentation here explicitly says it does not affect connectivity:

List of ports to expose from the container. Exposing a port here gives the system additional information about the network connections a container uses, but is primarily informational. Not specifying a port here DOES NOT prevent that port from being exposed. Any port which is listening on the default "0.0.0.0" address inside a container will be accessible from the network. Cannot be updated.

Now it seems it does not really affect anything and only informational, but what does that really mean, where is that used?

I have found one use of that is that if port defines a name, it can be referenced from a service by that name.

Is that it or there are some other uses for this specification?

-- Ilya Chernomordik
kubernetes
kubernetes-container
kubernetes-deployment
kubernetes-networking
kubernetes-service

2 Answers

7/25/2019

As you quote the documentation,

List of ports to expose from the container. Exposing a port here gives the system additional information about the network connections a container uses, but is primarily informational. Not specifying a port here DOES NOT prevent that port from being exposed. Any port which is listening on the default "0.0.0.0" address inside a container will be accessible from the network. Cannot be updated.

the purpose of defining the containerPorts is purely for documentation. It is only used by other developers to understand the port that the container listens to. Kubernetes borrows this idea from docker which does the same with EXPOSE command as mentioned here.

-- Malathi
Source: StackOverflow

7/25/2019

Container in the pod share network namespace which means IP,Routes etc stuff. Ports are not shared among containers. Each container need to have specific port in order expose its service.

When a container expose more than two ports, it need to use port name , so other k8s abstraction such as service, can find the correct port.

Kubernetes IP addresses exist at the Pod scope - containers within a Pod share their network namespaces - including their IP address. This means that containers within a Pod can all reach each other’s ports on localhost. This also means that containers within a Pod must coordinate port usage, but this is no different from processes in a VM. This is called the “IP-per-pod” model.kubernetes-network-model

-- Suresh Vishnoi
Source: StackOverflow