Ports
In all the previous sections, we have seen creating the pods, replicasets, and deployments, but we haven't gone through how to access pods inside the K8's cluster or outside the cluster. Services will come in handy to access pods outside the cluster. I will explain the terminologies first before we dive into it.
Let us use this pod.yaml to demonstrate the different types of ports available in the Kubernetes cluster. It often confuses most of them, which I am going to explain to you with examples.
download code here Github: portsdemo.yaml
kind: Pod
metadata:
name: portsdemo
spec:
containers:
- iam7hills/learnkubernetes:podsdemo-1.0
name: portsdemo
ports:
- containerPort: 80
ContainerPort:
In my example, I have used "podsdemo-1.0", which is a nginx container running on the listenerport "80". In case, if you are using the Tomcat app running on port 8080, then your containerPort should be same as your listener port 8080. In simple words, your listener port should match with your containerPort in your yaml file. Below is my nginx configuration, that is how I know that my listener port is 80.
nginx configuration file - FYI
listen 80;
root /usr/share/nginx/html;
}
hostNetwork: true
Let us assume that I need to access the below pod that was created using "portsdemo.yaml"
kubectl get pods portsdemo -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE
portsdemo 1/1 Running 0 29s 192.168.181.41 iam7hills <none> <none>
In the above example, you cannot access your application, because your pods running inside the Kubernetes cluster is not visible outside the cluster. You will get the connection refused. To fix this problem, I am going to add "hostNetwork: true" within the spec in the yaml as shown below. And then rerun the yaml.
kind: Pod
metadata:
name: portsdemo
spec:
hostNetwork: true
containers:
- iam7hills/learnkubernetes:podsdemo-1.0
name: portsdemo
ports:
- containerPort: 80
From your user browser, you need to access your application as http://<workernode>:80. In my case, it is going to be http://192.168.86.30:80; 80 is my nginx listener port waiting for the request to handle.