<p>I was under the impression in Kubernetes the way you expose a port for your application was by first exposing it in the Dockerfile using <code>EXPOSE</code>, then setting the <code>containerPort</code> setting in the deployment yaml file, and finally setting the <code>targetPort</code> in the service yaml file. I thought these all had to be the same value e.g. <code>7214</code>.</p>
<p>However I've just noticed that I've had the incorrect port exposed in one my applications Dockerfile as <code>7124</code> (but have the correct port in the other two files) like so :</p>
<p><strong>Dockerfile</strong></p>
<pre><code>expose 7124 #This is incorrect
</code></pre>
<p><strong>Deployment.yaml</strong></p>
<pre><code>ports:
  - containerPort: 7214
</code></pre>
<p><strong>Service.yaml</strong></p>
<pre><code>apiVersion: v1
kind: Service
metadata:
 name: my-service
spec:
 type: NodePort
 ports:
  - port: 7214
    targetPort: 7214
</code></pre>
<p>However my other applications are hitting the service fine and the requests are being forwarded onto the application at port <code>7214</code> without issue.</p>
<p>Why is this working? Is it not required for me to expose the port in the Dockerfile at all? Does <code>containerPort</code> take precedence or something? <a href="https://stackoverflow.com/a/57565261/3275784">This users</a> answer on a similar question says the exposed port doesn't have to match, but doesn't explain why.</p>

user3275784
<p>The port on which a process is listening is only known to the developer of the process as the port binding happens in code. <code>EXPOSE</code> and <code>containerPort</code> are ways to communicate this to outside world.</p>
<p><code>EXPOSE</code> directive in the Dockerfile doesn't do anything other than acting as documentation for the person reading your dockerfile to understand which port the process in the container might be listening on and for some UI purpose when you run <code>docker ps</code> command. It's like a communication between the author of the dockerfile and another person who might be using your image or modifyng your dockerfile.</p>
<p>Even the <code>containerPort</code> section in your deployment.yaml has no affect on anything. It also acts as documentation for people reading your manifest to know on which ports your process within the pod might be listening on. Another use is that you can give a name to the port using the <code>name</code> field and then you can reference this port by name in other places like the service object.</p>
<p>The only thing that matters is the actual port that your process is listening on in the container and making sure that port is used in <code>targetPort</code> field in the service port.</p>
