Use of containerPort in kubernetes POD definition

Viewed 1491

What is the use of specifying containerPort in the kubernetes POD definition ? Does it provide any extra benefit if we specify the container port in the yaml definition file ?

I observed that i can still access the port inside the container even if i omit it in POD yaml definition file.

2 Answers

It's informational.

From Kubernetes API Spec

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.

In pod manifest file, under pod spec, you need to define the container spec. This spec carries information like container image name and image version to be fetched from Docker hub or custom repository.
In container spec you need to define port which container is going to use.This can be defined by containerPort directive in the container spec of pod manifest.

“containerPort” defines the port on which app can be reached out inside the container.

To expose a pod to external world you need to create a service typically by a LoadBalancer.In Service.yaml configuration there are two types for port

  • port
  • targetPort

Service receives traffic on the "Port" directive of service object YAML.Then it redirect traffic recieved on "Port" to "targetPort"

targetPort and containerPort must be identical most of the time because whatever port is open for your application in a container that would be the same port you will wish to send traffic from service via targetPort

Related