Search code examples
kubernetescontainersportkubernetes-pod

Difference between Container port and targetport in Kubernetes?


How is container port different from targetports in a container in Kubernetes? Are they used interchangeably, if so why?

I came across the below code snippet where containerPort is used to denote the port on a pod in Kubernetes.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: postgres-deployment
  labels:
    app: demo-voting-app
spec:
  replicas: 1
  selector:
    matchLabels:
      name: postgres-pod
      app: demo-voting-app
  template:
    metadata:
      name: postgres-pod
      labels:
        name: postgres-pod
        app: demo-voting-app

    spec:
      containers:
      - name: postgres
        image: postgres:9.4
        ports:
        - containerPort: 5432
        

In the above code snippet, they have given 5432 for the containerPort parameter (in the last line). So, how is this containerPort different from targetport?

As far as I know, the term port in general refers to the port on the service (Kubernetes). Correct me if I'm incorrect.


Solution

  • In a nutshell: targetPort and containerPort basically refer to the same port (so if both are used they are expected to have the same value) but they are used in two different contexts and have entirely different purposes.

    They cannot be used interchangeably as both are part of the specification of two distinct kubernetes resources/objects: Service and Pod respectively. While the purpose of containerPort can be treated as purely informational, targetPort is required by the Service which exposes a set of Pods.

    It's important to understand that by declaring containerPort with the specific value in your Pod/Deployment specification you cannot make your Pod to expose this specific port e.g. if you declare in containerPort field that your nginx Pod exposes port 8080 instead of default 80, you still need to configure your nginx server in your container to listen on this port.

    Declaring containerPort in Pod specification is optional. Even without it your Service will know where to direct the request based on the info it has declared in its targetPort.

    It's good to remember that it's not required to declare targetPort in the Service definition. If you omit it, it defaults to the value you declared for port (which is the port of the Service itself).