<p>I'm trying to learn Kubernetes. One thing I don't understand is the following scenario:</p>
<p>Given I have a pod with 2 containers. One container runs an app listening on port 80, the other container is a sidecar which does some polling from a web resource but doesn't listen on any port.</p>
<p>Now when I start a service with <code>TargetPort</code> = 80, how does Kubernetes know which container within the pod exposes this port? Does it inspect all containers to check for exposed ports? Or does it just do a mapping for port 80 on <strong>all</strong> containers within the pod?</p>
<p>Additionally, is it possible to change the containers exposed port in Kubernetes, so the port the container exposes (=<code>containerPort</code>) maps to a different port <em>within</em> the container?
I mean something similar like the <em>-p</em> argument in Docker.</p>

Tobias von Falkenhayn
<p>The Kubernetes overview documentation of <a href="https://kubernetes.io/docs/concepts/workloads/pods/#pod-networking" rel="noreferrer">Pods</a> notes:</p>
<blockquote>
<p>Every container in a Pod shares the network namespace....  Within a Pod, containers share an IP address and port space....</p>
</blockquote>
<p>So if you have multiple containers in a Pod, from outside that Pod, they all look &quot;the same&quot;, in the same way that you could have multiple server processes running on a single physical machine with a single IP address.  You can't run two containers that listen on the same port in the same Pod.  The inbound request will reach whichever of the containers happens to be listening on that port (if any).</p>
<blockquote>
<p>Is it possible to change the containers exposed port in Kubernetes, so the port the container exposes (=containerPort) maps to a different port within the container?</p>
</blockquote>
<p>You can do this with your Service.  Remember that you don't generally connect directly to a Pod; instead, you connect to a Service and that forwards the request on to one of the matching Pods.  So if your Pod spec says</p>
<pre class="lang-yaml prettyprint-override"><code>containers:
  - name: sidecar
    # ...
  - name: server
    ports:
      - name: http
        containerPort: 8080
</code></pre>
<p>then the corresponding Service can say</p>
<pre class="lang-yaml prettyprint-override"><code>ports:
  - port: 80
    targetPort: http
</code></pre>
<p>and you'll connect to <code>http://service-name.namespace.svc.cluster.local</code> using the default HTTP port 80, even if the container process is actually listening on port 8080 or 3000 or whatever else.</p>
