<p>How is <code>container port</code> different from <code>targetports</code> in a container in Kubernetes?
Are they used interchangeably, if so why?</p>
<p>I came across the below code snippet where <code>containerPort</code> is used to denote the <code>port</code> on a pod in Kubernetes.</p>
<pre><code>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
        
</code></pre>
<p>In the above code snippet, they have given 5432 for the <code>containerPort</code> parameter (in the last line). So, how is this <code>containerPort</code> different from <code>targetport</code>?</p>
<p>As far as I know, the term <code>port</code> in general refers to the <code>port</code> on the <code>service</code> (Kubernetes). Correct me if I'm incorrect.</p>

Purushothaman Srikanth
<p><strong>In a nutshell:</strong> <code>targetPort</code> and <code>containerPort</code> 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.</p>
<p>They cannot be used interchangeably as both are part of the specification of two distinct kubernetes resources/objects: <code>Service</code> and <code>Pod</code> respectively. While the purpose of <code>containerPort</code> can be treated as purely informational, <code>targetPort</code> is required by the <code>Service</code> which exposes a set of <code>Pods</code>.</p>
<p>It's important to understand that by declaring <code>containerPort</code> with the specific value in your <code>Pod</code>/<code>Deployment</code> specification you cannot make your <code>Pod</code> to expose this specific port e.g. if you declare in <code>containerPort</code> field that your nginx <code>Pod</code> exposes port <code>8080</code> instead of default <code>80</code>, you still need to configure your nginx server in your container to listen on this port.</p>
<p>Declaring <code>containerPort</code> in <code>Pod</code> specification is optional. Even without it your <code>Service</code> will know where to direct the request based on the info it has declared in its <code>targetPort</code>.</p>
<p>It's good to remember that it's not required to declare <code>targetPort</code> in the <code>Service</code> definition. If you omit it, it defaults to the value you declared for <code>port</code> (which is the port of the <code>Service</code> itself).</p>
