使用 kubectl get events 命令可以深入了解 Kubernetes 集群中发生的事件。这些信息对于排除应用程序和基础架构中的故障至关重要。
下面的示例展示了如何从群集中检索事件,这有助于发现问题,如部署失败或 pod 调度问题。
【代码清单】
# Get all events in the cluster
kubectl get events --sort-by='.metadata.creationTimestamp'
# Get events for a specific namespace
kubectl get events -n my-namespace
# Get events for a specific resource, e.g., a pod
kubectl get events --field-selector involvedObject.name=my-pod
【执行结果】
LAST SEEN TYPE REASON OBJECT MESSAGE
1m Normal Scheduled pod/my-pod Successfully assigned default/my-pod to node-1
1m Normal Pulling pod/my-pod Pulling image "nginx:latest"
1m Normal Pulled pod/my-pod Successfully pulled image "nginx:latest"
1m Normal Created pod/my-pod Created container my-container
1m Normal Started pod/my-pod Started container my-container
kubectl get events 命令会列出群集中的事件,并按其创建时间戳排序。该命令会显示各种类型的事件,如正常操作(如 pod 调度、图像提取)和警告(如健康检查失败)。通过过滤特定资源的事件,您可以关注与特定 pod 或部署相关的问题,从而更容易诊断问题。
【小知识】
事件类型: 事件可分为 “正常 ”和 “警告”,帮助您快速识别可能需要注意的问题。
事件 TTL:事件存储在 etcd 中的默认存活时间(TTL)为一小时,一小时后会自动删除。
自定义事件: 您可以在应用程序中创建自定义事件来记录特定事件,这有助于监控和调试。