kubectl exec, logs, and port-forward

Debug running containers, stream logs, inspect previous crashes, and forward local ports into the cluster.

Why These Commands Matter

Once workloads are running, the next challenge is seeing what they are doing. exec, logs, and port-forward are some of the most practical debugging tools in Kubernetes.

Run a Command Inside a Pod

kubectl exec -it my-pod -- sh
kubectl exec -it my-pod -- bash

Use sh when bash is not installed in the container image.

If the pod has multiple containers:

kubectl exec -it my-pod -c app -- sh

Read Logs

kubectl logs my-pod
kubectl logs my-pod -c app

Follow Logs Live

kubectl logs -f my-pod

This is useful when watching a startup sequence or investigating a live problem.

Read Logs from a Crashed Container

kubectl logs --previous my-pod

That command is especially useful when a container restarts quickly and the current logs no longer show the first failure.

Port Forward into the Cluster

kubectl port-forward pod/my-pod 8080:80
kubectl port-forward service/web 8080:80

This opens a local port on your machine and forwards traffic to a pod or service in the cluster.

Think of port-forward as a temporary private tunnel into the cluster for testing and debugging.

A Practical Debug Loop

kubectl logs my-pod
kubectl logs --previous my-pod
kubectl exec -it my-pod -- sh
kubectl port-forward service/web 8080:80

When to Use What

CommandBest for
kubectl logsSeeing application stdout and stderr
kubectl execInspecting container state from inside
kubectl port-forwardTesting cluster services from your laptop

Caution

Avoid treating exec as the main way to operate production apps. It is a debugging tool, not a substitute for good observability or proper configuration management.

Exercise

Previous Logs

Which command helps you inspect the logs from the last crashed container instance?

Exercise

Port Forward Use

Why would you use `kubectl port-forward service/web 8080:80`?

Continue Learning

Explore Related Topics

Try the Tool

Related Resources