Important tips
Set imagePullPolicy to IfNotPresent unless you have a strong reason for using Always or Never. This will ensure that your containers boot up quickly and you don’t download images unnecessarily.
Always use resource requests and limits while scheduling pods. These ensure that your pod is scheduled in an appropriate node and does not exhaust any existing resources. You can also apply a default resource policy at the cluster level to ensure that your developers don’t cause any harm if they miss out on this section for some reason.
Let’s apply the manifest using the following command:
$ kubectl apply -f nginx-pod.yaml
The pod that we created is entirely out of bounds from the host. It runs within the container network, and by default, Kubernetes does not allow any pod to be exposed to the host network unless we explicitly want to expose it.
There are two ways to access the pod – using port forwarding with kubectl port-forward, or exposing the pod through a Service resource.
Using port forwarding
Before we get into the service side of things, let’s consider using the port-forward option.
To expose the pod using port forwarding, execute the following command:
$ kubectl port-forward nginx 8080:80
Forwarding from 127.0.0.1:8080 -> 80
Forwarding from [::1]:8080 -> 80
The prompt is stuck here. This means it has opened a port forwarding session and is listening on port 8080. It will automatically forward the request it receives on port 8080 to NGINX port 80.
Open a duplicate Terminal session and curl on the preceding address to see what we get:
$ curl 127.0.0.1:8080
…
<title>Welcome to nginx!</title>
…
We can see that it is working as we get the default NGINX response.
Now, there are a few things to remember here.
When we use HTTP port-forward, we are forwarding requests from the client machine running kubectl to the pod, something similar to what’s shown in the following diagram:
Figure 5.2 – kubectl port-forward
When you run kubectl port-forward, the kubectl client opens a TCP tunnel via the Kube API server, and the Kube API server then forwards the connection to the correct pod. As the connection between the kubectl client and the API server is encrypted, it is a very secure way of accessing your pod, but hold your horses before deciding to use kubectl port-forward to expose pods to the outside world.
There are particular use cases for using kubectl port-forward:
- For troubleshooting any misbehaving pod.
- For accessing an internal Kubernetes service, such as the Kubernetes dashboard – that is, when you don’t want to expose the service to the external world but only allow Kubernetes admins and users to log into the dashboard. It is assumed that only these users will have access to the cluster via kubectl.
For anything else, you should use Service resources to expose your pod, internally or externally. While we will cover the Service resource in the next chapter, let’s look at a few operations we can perform with a pod.