Similar to how we can browse logs from a container using docker logs, we can browse logs from a container within a Kubernetes pod using the kubectl logs command. If more than one container runs within the pod, we can specify the container’s name using the -c flag.
To access the container logs, run the following command:
$ kubectl logs nginx -c nginx
…
127.0.0.1 – – [18/Jun/2023:14:08:01 +0000] “GET / HTTP/1.1” 200 612 “-” “curl/7.47.0” “-“
As the pod is running a single container, we need not specify the -c flag, so instead, you can use the following command:
$ kubectl logs nginx
There might be instances where you may want to get a shell to a running container and troubleshoot what’s going on within that. We use docker exec for that in the Docker world. Similarly, we can use kubectl exec for that within Kubernetes.
Run the following command to open a shell session with the container:
$ kubectl exec -it nginx — /bin/bash
root@nginx:/# cd /etc/nginx/ && ls
conf.d fastcgi_params mime.types modules nginx.conf scgi_params uwsgi_params root@nginx:/etc/nginx# exit
You can even run specific commands without opening a shell session. For example, we can perform the preceding operation with a single line, something like the following:
$ kubectl exec nginx — ls /etc/nginx
conf.d fastcgi_params mime.types modules nginx.conf scgi_params uwsgi_params
kubectl exec is an important command that helps us troubleshoot containers.
Tip
If you modify files or download packages within the container in exec mode, they will persist until the current pod is alive. Once the pod is gone, you will lose all changes. Therefore, it isn’t a great way of fixing issues. You should only diagnose problems using exec, bake the correct changes in a new image, and then redeploy it.
When we looked at distroless containers in the previous chapter, they did not allow exec into the container for security reasons. There are debug images available for distroless that will enable you to open a shell session for troubleshooting purposes if you wish.
Tip
By default, a container runs as the root user if you don’t specify the user within the Dockerfile while building the image. You can set a runAsUser attribute within your pod’s security context if you want to run your pod as a specific user, but this is not ideal. The best practice is to bake the user within the container image.