Kubernetes (kubectl) 徹底解説 — 60+ コマンドを 8 カテゴリで
Kubernetes 案件は単価が伸びやすい領域。EKS / GKE / AKS / Self-managed の違いはあれど kubectl の使い方は共通。
本記事は CRUD 操作からデバッグ、ロールアウト戦略まで 60+ コマンドを整理します。
目次
- context / namespace
- リソース一覧・詳細 (get / describe)
- apply / delete / patch / edit
- ログ・exec・cp・port-forward
- rollout / scale / autoscale
- node / events / top
- RBAC・Secret・ConfigMap
- よく使うアドオン (kubens / k9s / stern)
- 障害対応レシピ
- 用語集
1. context / namespace
# context(接続先クラスタ + 認証情報 + namespace)
kubectl config get-contexts
kubectl config current-context
kubectl config use-context my-cluster
kubectl config rename-context old new
kubectl config delete-context old
# namespace
kubectl get ns
kubectl create ns dev
kubectl delete ns dev
# デフォルト namespace 設定
kubectl config set-context --current --namespace=dev
# kubeconfig マージ
KUBECONFIG=~/.kube/config:~/.kube/config-eks kubectl config view --merge --flatten > ~/.kube/merged
mv ~/.kube/merged ~/.kube/config
# AWS EKS の context を取り込む
aws eks update-kubeconfig --name my-cluster --region ap-northeast-1
2. リソース一覧・詳細
kubectl get pods # 現 namespace
kubectl get pods -A # 全 namespace
kubectl get pods -n kube-system
kubectl get pods -o wide # IP / Node も表示
kubectl get pods --selector=app=web # ラベル絞り込み
kubectl get pods -l 'env in (prod,stg)'
kubectl get pods --field-selector=status.phase=Failed
kubectl get pods -w # watch (変化追跡)
# 形式
kubectl get pod web-xxx -o yaml
kubectl get pod web-xxx -o json
kubectl get pod web-xxx -o jsonpath='{.status.podIP}'
kubectl get pods -o custom-columns='NAME:.metadata.name,IP:.status.podIP'
# 各種リソース
kubectl get deploy / svc / ing / cm / secret / pv / pvc / sa / role / rolebinding / hpa
kubectl get all -n my-ns # 主要リソース横断
kubectl api-resources # 全リソース型一覧
kubectl api-versions
# describe (events 含む詳細)
kubectl describe pod web-xxx
kubectl describe deployment web
kubectl describe node ip-10-0-0-5.ap-northeast-1.compute.internal
3. apply / delete / patch / edit
kubectl apply -f manifest.yaml # 作成 / 更新
kubectl apply -f ./k8s/ # ディレクトリ
kubectl apply -k ./overlays/prod # Kustomize
kubectl apply -f - << 'EOF'
apiVersion: v1
kind: ConfigMap
metadata:
name: app
data:
LOG_LEVEL: debug
EOF
kubectl create -f manifest.yaml # 既存ならエラー
kubectl replace -f manifest.yaml # 置換
kubectl delete -f manifest.yaml
kubectl delete deploy web
kubectl delete pod web-xxx --grace-period=0 --force # 強制削除
# 部分更新
kubectl patch deploy web -p '{"spec":{"replicas":5}}'
kubectl patch deploy web --type='json' \
-p '[{"op":"replace","path":"/spec/replicas","value":5}]'
# その場編集
kubectl edit deploy web # $EDITOR でその場編集
# diff
kubectl diff -f manifest.yaml
# dry-run
kubectl apply -f manifest.yaml --dry-run=client -o yaml
kubectl apply -f manifest.yaml --dry-run=server
4. ログ・exec・cp・port-forward
# logs
kubectl logs web-xxx
kubectl logs web-xxx -c container-name # マルチコンテナ
kubectl logs web-xxx -f # tail -f
kubectl logs web-xxx --since=10m
kubectl logs web-xxx --tail=200
kubectl logs web-xxx --previous # 前回 crash 時のログ
kubectl logs -l app=web --max-log-requests=10 -f # ラベルで複数 Pod 同時 tail
# exec
kubectl exec -it web-xxx -- bash
kubectl exec web-xxx -- ls /etc
kubectl exec -it web-xxx -c sidecar -- sh # マルチコンテナ
# ファイル コピー
kubectl cp ./local.txt my-ns/web-xxx:/tmp/
kubectl cp my-ns/web-xxx:/var/log/app.log ./
# port-forward
kubectl port-forward pod/web-xxx 8080:80
kubectl port-forward svc/web 8080:80
kubectl port-forward deploy/web 8080:80
5. rollout / scale / autoscale
# rollout (Deployment 更新)
kubectl rollout status deploy/web
kubectl rollout history deploy/web
kubectl rollout history deploy/web --revision=3
kubectl rollout undo deploy/web # 直前に戻す
kubectl rollout undo deploy/web --to-revision=2
kubectl rollout pause deploy/web # 一時停止
kubectl rollout resume deploy/web
kubectl rollout restart deploy/web # 強制再起動
# scale
kubectl scale deploy web --replicas=5
kubectl scale deploy web --current-replicas=3 --replicas=5 # 現状確認しつつ
kubectl scale --replicas=0 deploy/web # 一時停止相当
# HPA (Horizontal Pod Autoscaler)
kubectl autoscale deploy web --min=2 --max=10 --cpu-percent=70
kubectl get hpa
kubectl describe hpa web
# Image 更新(rollout 系の最速)
kubectl set image deploy/web web=myapp:1.2.3 --record
kubectl set env deploy/web LOG_LEVEL=debug
6. node / events / top
kubectl get nodes
kubectl describe node ip-10-0-0-5.ap-northeast-1.compute.internal
kubectl top node # CPU/Mem (要 metrics-server)
kubectl top pod -A
kubectl top pod -l app=web --containers
# node 操作
kubectl cordon NODE # 新規 Pod スケジュール禁止
kubectl uncordon NODE
kubectl drain NODE --ignore-daemonsets --delete-emptydir-data # 退避してから停止
# events(クラスタ内で起きたこと)
kubectl get events --sort-by='.lastTimestamp'
kubectl get events -n my-ns --field-selector type=Warning
kubectl get events --watch # リアルタイム
7. RBAC・Secret・ConfigMap
# RBAC
kubectl get sa / role / rolebinding / clusterrole / clusterrolebinding -A
kubectl create sa my-sa
kubectl create role pod-reader --verb=get,list --resource=pods
kubectl create rolebinding pod-reader-binding --role=pod-reader --serviceaccount=my-ns:my-sa
# 自分の権限確認
kubectl auth can-i list pods
kubectl auth can-i delete pods --as=system:serviceaccount:my-ns:my-sa
# Secret
kubectl create secret generic my-secret --from-literal=KEY=value
kubectl create secret generic my-secret --from-file=./secret.txt
kubectl create secret docker-registry regcred --docker-server=... --docker-username=... \
--docker-password=... --docker-email=...
# Secret を覗く
kubectl get secret my-secret -o jsonpath='{.data.KEY}' | base64 -d
# ConfigMap
kubectl create cm app-config --from-literal=LOG_LEVEL=info
kubectl create cm app-config --from-file=./config/
kubectl get cm app-config -o yaml
# Secret/CM を Pod から参照は manifest 側 envFrom / volumeMounts
8. よく使うアドオン
# kubens / kubectx (namespace / context 切替)
kubens # 一覧
kubens dev # 切替
kubectx # context 一覧
kubectx my-cluster # context 切替
# k9s(TUI)
k9s
# 矢印キーでナビゲート、l = logs、s = shell、d = describe、Ctrl+d = delete
# stern (複数 Pod ログ tail)
stern app- # prefix マッチ全 Pod
stern -l app=web --tail 100
# kubie (会話的 namespace/context)
kubie ctx
kubie ns
# helm(パッケージマネージャ)
helm install myapp ./chart
helm upgrade myapp ./chart -f values-prod.yaml
helm rollback myapp 1
helm list
helm uninstall myapp
障害対応レシピ
レシピ 1 — Pod が CrashLoopBackOff
kubectl get pods # 状態確認
kubectl describe pod CRASH_POD # Events を見る
kubectl logs CRASH_POD --previous # 前回 crash 時のログ
kubectl logs CRASH_POD -c init-xxx # init container 落ちてないか
kubectl get events --sort-by='.lastTimestamp' | tail -n 20
レシピ 2 — Pod が Pending のまま
kubectl describe pod PENDING_POD # Events に "FailedScheduling" 等
kubectl get nodes # ノード足りる?
kubectl describe nodes | grep -A5 'Allocated resources'
# nodeSelector / taints / tolerations / resources の不一致が大半
レシピ 3 — DNS が引けない
kubectl exec -it any-pod -- nslookup kubernetes.default
kubectl exec -it any-pod -- cat /etc/resolv.conf
kubectl get pods -n kube-system | grep coredns # CoreDNS 動いてる?
kubectl logs -n kube-system -l k8s-app=kube-dns
レシピ 4 — Service につながらない
kubectl get svc
kubectl describe svc web # Endpoints が空 = selector ミスマッチ
kubectl get endpoints web
kubectl get pods --show-labels # Pod label と svc selector を比較
kubectl exec -it any-pod -- curl http://web.my-ns.svc.cluster.local:80
レシピ 5 — ロールアウト失敗の即座 rollback
kubectl rollout status deploy/web # ハング検出
kubectl rollout history deploy/web
kubectl rollout undo deploy/web --to-revision=PREV_OK
レシピ 6 — node 退避してメンテ
kubectl cordon NODE # 新規スケジュール禁止
kubectl drain NODE --ignore-daemonsets --delete-emptydir-data
# 作業
kubectl uncordon NODE
コマンド早見表
# 基本
kubectl get pods -A -o wide
kubectl describe pod P
kubectl logs -f -l app=web --max-log-requests=10
kubectl exec -it P -- bash
# 更新
kubectl apply -f file.yaml
kubectl set image deploy/D C=image:tag
kubectl rollout undo deploy/D --to-revision=N
kubectl rollout restart deploy/D
# port-forward / cp
kubectl port-forward svc/web 8080:80
kubectl cp local file ns/pod:/tmp/
# context
aws eks update-kubeconfig --name C --region R
kubectl config use-context X
kubectl config set-context --current --namespace=NS
用語集
- Pod
- K8s の最小単位。1 個以上のコンテナを共通 NW/IPC 名前空間で束ねた実行単位。
- Deployment / ReplicaSet / StatefulSet / DaemonSet / Job / CronJob
- Pod を管理するコントローラ。Deployment = 通常アプリ、StatefulSet = ステートフル、DaemonSet = 全 Node 1 個、Job = バッチ、CronJob = 定期。
- Service / Ingress
- Service = Pod 群への安定エンドポイント (ClusterIP / NodePort / LoadBalancer)。Ingress = HTTP L7 ルータ + TLS 終端。
- ConfigMap / Secret
- 設定値 / 機密値を Pod に注入するリソース。env / volume として参照。
- namespace
- 論理的な分離単位。リソース名は namespace 内でユニーク。
- context / kubeconfig
- kubeconfig = 接続情報の YAML ファイル (~/.kube/config)。context = cluster + user + namespace の組合せ。
- RBAC (Role / RoleBinding / ClusterRole / ClusterRoleBinding)
- K8s の認可。Role = namespace スコープ、ClusterRole = クラスタスコープ。Binding で Subject と紐付け。
- HPA (Horizontal Pod Autoscaler)
- CPU / メモリ / カスタムメトリクスに応じて Pod レプリカ数を自動調整。
metrics-server必須。 - rollout
- Deployment の段階的更新。RollingUpdate がデフォルト、戦略は
maxSurge/maxUnavailableで調整。 - cordon / drain / uncordon
- cordon = 新規 Pod スケジュール禁止 / drain = 退避 + cordon / uncordon = 解除。Node メンテナンスに使う。
- taint / toleration
- Node に taint を付けると、対応する toleration を持つ Pod のみ配置可能。専用 Node の予約に。
- nodeSelector / nodeAffinity
- Pod が配置される Node の希望条件。GPU node に限定する等。
- CoreDNS
- K8s クラスタ内 DNS。
service.namespace.svc.cluster.local形式で名前解決。 - EKS / GKE / AKS
- AWS / GCP / Azure のマネージド K8s。Control Plane の運用が不要になる。
- kustomize / Helm
- kustomize = ベース + オーバーレイで manifest 生成。Helm = Chart + values でテンプレート化。両方とも実用。
- k9s / stern / kubectx / kubens
- kubectl の人気アドオン。k9s = TUI、stern = 複数 Pod ログ、kubectx/kubens = context/namespace 切替。