Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Using kubectl logs and exec

1. Introduction

Kubernetes is an open-source platform for automating deployment, scaling, and operations of application containers. Monitoring and logging are critical for troubleshooting and ensuring the health of applications running in a Kubernetes cluster. In this lesson, we will explore two essential commands: kubectl logs for viewing logs of your pods and kubectl exec for executing commands inside a container.

2. kubectl logs

The kubectl logs command retrieves logs from a container in a pod. This is essential for debugging issues in your applications.

2.1 Syntax

kubectl logs [POD_NAME] [-c CONTAINER_NAME] [OPTIONS]

2.2 Example Usage

kubectl logs my-pod
kubectl logs my-pod -c my-container
kubectl logs my-pod --previous

In this example:

  • The first command fetches logs from the default container in my-pod.
  • The second command fetches logs from a specific container my-container.
  • The third command retrieves logs from the previous instance of the container if it has crashed.

2.3 Important Notes

Logs are ephemeral; if a pod is deleted, its logs are also lost unless a logging solution is implemented.

3. kubectl exec

The kubectl exec command allows you to execute commands directly inside a running container. This is useful for debugging and troubleshooting.

3.1 Syntax

kubectl exec [POD_NAME] [-c CONTAINER_NAME] -- COMMAND [ARG...]

3.2 Example Usage

kubectl exec my-pod -- ls /app
kubectl exec my-pod -c my-container -- /bin/bash

In this example:

  • The first command lists files in the /app directory of the my-pod.
  • The second command opens a bash shell in the specified container.

3.3 Important Notes

Be cautious when executing commands in containers, as you can modify the state of your application.

4. Best Practices

  • Integrate a centralized logging solution (e.g., ELK stack, Fluentd) for persistent log storage.
  • Use kubectl logs with filters to narrow down logs based on time or severity.
  • Limit the use of kubectl exec to troubleshooting; prefer automated solutions.
  • Regularly monitor logs for anomalies to proactively address issues.

5. FAQ

Can I access logs from all containers in a pod?

Yes, use the -c option to specify the container name if there are multiple containers in the pod.

What if my pod crashes and I want to view its logs?

You can use the --previous flag with kubectl logs to view logs from the last terminated container.

Aren't logs automatically stored somewhere?

No, logs in Kubernetes are not stored automatically. You should implement a logging solution for long-term storage.