I'm trying to understand the purpose of the `containerPort` field in a Kubernetes Pod spec. For example, in my `mysql-server` Pod configuration, I have it set to port 3306 like this:
```yaml
apiVersion: v1
kind: Pod
metadata:
name: mysql-server
spec:
containers:
- name: mysql
image: mysql:8
env:
- name: MYSQL_ROOT_PASSWORD
value: "..."
ports:
- containerPort: 3306
```
Even if I remove the `ports` section, the MySQL server still works and listens on port 3306. I can access it through a service:
```yaml
apiVersion: v1
kind: Service
metadata:
name: mysql-service
spec:
selector:
...
ports:
- protocol: TCP
port: 12345
targetPort: 3306
type: ClusterIP
```
Or even through port forwarding:
```bash
kubectl port-forward pod/mysql-server --address=... 55555:3306
```
So, what's the actual benefit of defining the `containerPort`? Is it similar to the `EXPOSE` command in a Dockerfile, serving more as documentation?
3 Answers
The `containerPort` acts as a form of metadata. Other tools can rely on it to identify which port the Pod expects incoming traffic on. So even if everything works without it, having the port defined is useful for anyone working with the configuration or using tools that benefit from that info.
I think it's mainly for clarity and documentation purposes, much like Docker's EXPOSE. There's no actual network magic happening just from these keywords; they indicate which port the application is expected to listen on. Also, some automation or tooling might leverage this setting.
Setting the `containerPort` in the Pod spec helps in naming the port so that it can easily be referenced by Services. If the Service uses a selector to target this Pod, it knows which port to forward traffic to without needing to guess. It's just good practice!
Exactly! It's about making configurations easier to achieve for people or tools that interact with your Pods.