🤖

kubectl でよく使うコマンド

に公開

🔍 基本操作(リソースの確認)

コマンド 説明
kubectl get pods Pod 一覧表示
kubectl get pods -o wide Pod 一覧 + ノード・IPなどの詳細情報付き
kubectl get pods -A または --all-namespaces 全NamespaceのPod一覧表示
kubectl get deploy -n <namespace> 指定NamespaceのDeployment一覧
kubectl get all -n <namespace> 指定Namespaceの主要リソース一覧

🔍 リソースの詳細表示

コマンド 説明
kubectl describe pod <pod-name> Pod の詳細を表示(イベントや状態など)
kubectl describe node <node-name> Node の詳細を表示

📜 ログの確認

コマンド 説明
kubectl logs <pod-name> Pod のログを表示(単一コンテナ)
kubectl logs -f <pod-name> リアルタイムでログをフォロー
kubectl logs <pod-name> -c <container-name> マルチコンテナPodの特定コンテナのログ表示
kubectl logs --since=10m <pod-name> 直近10分間のログを取得

🛠 Pod 操作

コマンド 説明
kubectl exec -it <pod-name> -- bash Pod に bash でシェル接続(Debian系)
kubectl exec -it <pod-name> -- /bin/sh Pod に sh でシェル接続(Alpine系)
kubectl delete pod <pod-name> Pod を削除(再作成されることが多い)
kubectl delete pod <pod-name> --grace-period=0 --force 強制削除(クラッシュなどで応答しないとき)

🔄 ポートフォワード(ローカルでPodにアクセス)

コマンド 説明
kubectl port-forward pod/<pod-name> 8080:80 ローカル8080 → Podの80番ポートに転送
kubectl port-forward svc/<service-name> 8080:80 ローカル → Service 経由でアクセス

📂 Namespace 関連

コマンド 説明
kubectl get ns Namespace 一覧表示
kubectl get pods -n <namespace> 指定NamespaceでのPod一覧表示
kubectl config set-context --current --namespace=<ns> デフォルトNamespaceを変更

📦 マニフェスト適用・変更

コマンド 説明
kubectl apply -f file.yaml マニフェストを適用(作成 or 更新)
kubectl delete -f file.yaml マニフェストで定義されたリソースを削除
kubectl diff -f file.yaml 適用前後の差分を表示
kubectl create -f file.yaml 新規作成のみ(存在する場合は失敗)
kubectl edit deploy <name> リアルタイムでリソースを編集(vimなどが起動)

📊 モニタリング・デバッグ

コマンド 説明
kubectl top pod Pod のCPU/メモリ使用量(metrics-serverが必要)
kubectl top node Node のリソース使用状況
kubectl get events 最近のイベント一覧(失敗や再起動の兆候)
kubectl rollout status deploy/<name> デプロイの進捗確認
kubectl rollout undo deploy/<name> デプロイのロールバック

💡 その他便利なオプション

オプション 説明
-n <namespace> 対象Namespaceを指定
-o yaml / -o json 出力形式をYAML/JSONで表示
--watch 変化をリアルタイムで監視
--selector=<key>=<value> ラベルでフィルター
--context=<context-name> kubeconfigのContextを切り替え

Discussion