kubectl-opslisted
Install: claude install-skill structure-projects/structure-agent-rules
# kubectl 使用
> 安全使用 kubectl 操作 K8s 集群。**生产写操作 MUST 用户确认**。
## 上下文与命名空间
```bash
# 查看当前上下文
kubectl config current-context
# 切换上下文(MUST 用户确认)
kubectl config use-context <context>
# 切换命名空间
kubectl config set-context --current --namespace=<ns>
# 临时指定命名空间(推荐)
kubectl -n <ns> get pods
```
## 查看操作(只读,安全)
```bash
# 查看 Pod
kubectl get pods
kubectl get pods -n <ns>
kubectl get pods -o wide # 含节点
kubectl get pods --watch # 监听变化
# 查看 Deployment
kubectl get deployment
kubectl describe deployment <name>
# 查看 Service
kubectl get svc
kubectl describe svc <name>
# 查看 Ingress
kubectl get ingress
# 查看所有资源
kubectl get all
# 查看事件(定位问题)
kubectl get events --sort-by='.lastTimestamp'
```
## 日志与调试
```bash
# 查看日志
kubectl logs <pod>
kubectl logs -f <pod> # 跟随
kubectl logs --tail=100 <pod> # 最后 100 行
kubectl logs <pod> -c <container> # 多容器 Pod
kubectl logs <pod> --previous # 上次崩溃前日志
# 进入容器
kubectl exec -it <pod> -- /bin/sh
kubectl exec -it <pod> -c <container> -- /bin/sh
# 端口转发(本地访问集群内服务)
kubectl port-forward pod/<pod> 8080:8080
kubectl port-forward svc/<svc> 8080:80
```
## 部署操作(写,MUST 确认)
```bash
# 应用 manifest
kubectl apply -f deployment.yaml
# 应用整个目录
kubectl apply -f ./k8s/
# 查看 diff(先预览再应用)
kubectl diff -f deployment.yaml
# 删除资源(MUST 用户确认)
kubectl delete -f deployment.yaml
kubectl delete pod <pod>
kubectl delete deployment <name>
```
## 滚动更新与回滚
```bash
# 查看滚动更新状态
kubectl rollout status deployment/<name>
# 查看历史
kubectl rollout history