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 EXPOSE, then setting the containerPort setting in the deployment yaml file, and finally setting the targetPort in the service yaml file. I thought these all had to be the same value e.g. 7214.
However I've just noticed that I've had the incorrect port exposed in one my applications Dockerfile as 7124 (but have the correct port in the other two files) like so :
Dockerfile
expose 7124 #This is incorrect
Deployment.yaml
ports:
- containerPort: 7214
Service.yaml
apiVersion: v1
kind: Service
metadata:
name: my-service
spec:
type: NodePort
ports:
- port: 7214
targetPort: 7214
However my other applications are hitting the service fine and the requests are being forwarded onto the application at port 7214 without issue.
Why is this working? Is it not required for me to expose the port in the Dockerfile at all? Does containerPort take precedence or something? This users answer on a similar question says the exposed port doesn't have to match, but doesn't explain why.