【k8s】Kubernetes ~ 基本編 / kubectlコマンド ~

■ はじめに

https://dk521123.hatenablog.com/entry/2020/04/27/224624
https://dk521123.hatenablog.com/entry/2020/05/01/000000
https://dk521123.hatenablog.com/entry/2020/05/04/013529

の続き。

kubectl コマンド について、メモしておく

目次

【0】kubectlコマンド
 1)インストール
 2)基本構文
 3)公式ドキュメント
 補足:Kubernetes のその他CLI
【1】情報を取得するコマンド一覧
 1)kubectl get
 2)kubectl describe
 3)kubectl cluster-info
 4)kubectl version
 5)kubectl diff
 6)kubectl logs 
【2】その他コマンド一覧
 1)kubectl apply
 2)kubectl config
 3)kubectl exec
 4)kubectl create
 5)kubectl expose
 6)kubectl port-forward
 7)kubectl proxy
 8)kubectl wait
 9)kubectl delete
 10)kubectl replace
 11)kubectl api-resources
【3】Tips
 使用例1:kubernetesでnamespaceが消えない場合の対処

【0】kubectlコマンド

* コマンド実行やKubernetesクラスターの管理に使うCLIツール
 => kubectl = Kubernetes control?
 =>  読み方「koob-control (クューブコントロール)」

1)インストール

* 以下の関連記事の「kubectlのインストール」を参照のこと

https://dk521123.hatenablog.com/entry/2023/05/10/220241

2)基本構文

https://kubernetes.io/ja/docs/reference/kubectl/overview/#%E6%A7%8B%E6%96%87

kubectl [command] [TYPE] [NAME] [flags]

command

* 実行したい操作
* e.g. create, get, describe, delete etc

TYPE

* リソースタイプ
* 短縮名も可
* e.g. pods, nodes, services

NAME

* リソース名

flags

* オプションフラグ
* e.g. -f <file_path>, -o json/wide/name/yaml (出力形式; output)

3)公式ドキュメント

* 公式サイト

https://kubernetes.io/ja/docs/reference/kubectl/overview/
[1] チートシート
https://kubernetes.io/ja/docs/reference/kubectl/cheatsheet/
[2] コマンド一覧
https://kubernetes.io/docs/reference/generated/kubectl/kubectl-commands

補足:Kubernetes のその他CLI

[1] kubeadm

* セキュアなKubernetesクラスターを簡単にプロビジョニングするためのCLIツール
 => クラスターを起動する などを行う

【1】情報を取得するコマンド一覧

* Kubernetesに関する情報を取得する主なコマンドを記す
 => トラブルシュートに使えそう
 => 詳細は、以下の公式サイトを参照のこと。

公式サイト
https://kubernetes.io/ja/docs/reference/kubectl/overview/#%E6%93%8D%E4%BD%9C
https://kubernetes.io/ja/docs/tutorials/kubernetes-basics/explore/explore-intro/

1)kubectl get

* リソースの一覧表示

構文

kubectl get (-f FILENAME | TYPE [NAME | /NAME | -l label]) \
  [--watch] [--sort-by=FIELD] [[-o | --output]=OUTPUT_FORMAT] [flags]

コマンド例

# ノードを表示
kubectl get pods
kubectl get pods -n node-name -w

# Deploymentに関する情報を表示
kubectl get deployments

# service の確認
$ kubectl get service
NAME             TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)   AGE
kubernetes       ClusterIP   10.96.0.1        <none>        443/TCP   35m
nginx-3zyl82du   ClusterIP   10.111.163.131   <none>        80/TCP    30s

# 現在の名前空間上にあるすべてのサービスのリストを表示します
kubectl get services

# ネームスペース一覧表示
kubectl get namespace

# ネームスペース(-n, --namespace <NEMESPACE>)を
# 指定してPod情報を取得
kubectl get pod -n your-namespace

# ネームスペースのリストをJSON形式で出力する
kubectl get ns airflow -o json > airflow.json
# kubectl get namespace airflow -o json > airflow.json

https://qiita.com/MahoTakara/items/a8b204dd183fc662926e

2)kubectl describe

* 単一リソースに関する詳細情報を表示

構文

kubectl describe (-f FILENAME | TYPE [NAME_PREFIX | /NAME | -l label]) [flags]

コマンド例

# リソース名「nginx-deployment」の詳細を表示
kubectl describe deployment nginx-deployment

# Node名「docker-desktop」の詳細を表示
kubectl describe node docker-desktop

# Namespace名「kube*」の詳細を表示
kubectl describe ns kube

3)kubectl cluster-info

* クラスタ情報を表示する
 => Kubernetesクラスターのマスターとサービスのアドレスを表示
 => どのKubernetesクラスタにつないでいるか確認するためのコマンド

構文

kubectl cluster-info [flags]

コマンド例

kubectl cluster-info

4)kubectl version

* クライアントとサーバーで実行中のKubernetesバージョンを表示

構文

kubectl version [--client] [flags]

コマンド例

# クライアントのKubernetesバージョンを表示
kubectl version --client

5)kubectl diff

* 「ファイル or 標準出力」と「現在の設定」との差分を表示

構文

kubectl diff -f FILENAME [flags]

コマンド例

# クラスターの現在の状態とマニフェストが適用された場合のクラスターの状態と比較
kubectl diff -f ./my-manifest.yaml

6)kubectl logs

* 単一Pod上の単一コンテナ内のログを表示

https://jamesdefabia.github.io/docs/user-guide/kubectl/kubectl_logs/

構文

kubectl logs POD [-c CONTAINER] [--follow] [flags]

# --tail=-1: Lines of recent log file to display. Defaults to -1, showing all log lines.

コマンド例

# name=mylabelラベルを持つPodのログをダンプ(標準出力) 
kubectl logs -l name=myLabel -c my-container

https://kubernetes.io/ja/docs/reference/kubectl/cheatsheet/#%E5%AE%9F%E8%A1%8C%E4%B8%AD%E3%81%AE%E3%83%9D%E3%83%83%E3%83%89%E3%81%A8%E3%81%AE%E5%AF%BE%E8%A9%B1%E5%87%A6%E7%90%86

【2】その他コマンド一覧

1)kubectl apply

* ファイルや標準出力から、リソースの適用や更新を行う

構文

kubectl apply -f FILENAME [flags]

コマンド例

# https://dk521123.hatenablog.com/entry/2020/05/04/013529  
# でサービス作成時に使用
kubectl apply -f ./nginx-service.yaml

2)kubectl config

* kubeconfigファイルを変更
 => 詳細は、以下の関連記事を参照のこと。

https://dk521123.hatenablog.com/entry/2023/05/24/211803

コマンド例

# [1] kubeconfigの設定を表示
kubectl config view

KUBECONFIG=~/.kube/kubconfig2 

# [1]' 設定が変更されたか確認
kubectl config view

# [2] コンテキストのリストを表示
kubectl config get-contexts

# [3] 現在のコンテキストを表示
kubectl config current-context

# [4] isMinikube = true を設定
pulumi config set isMinikube true

3)kubectl exec

* 単一Pod上の単一コンテナ内でコマンドを実行

https://jamesdefabia.github.io/docs/user-guide/kubectl/kubectl_exec/

用途

* Podの中に入ってデバッグするとか、、、

構文

# -i : interactive (相互)
# -t : terminal (ターミナル)
kubectl exec <pod_name> [-c <container_name>] [-i] [-t] [flags] [-- COMMAND [args...]]

# Podの中に入るコマンド構文
kubectl exec <pod_name> -c <container_name> -- /bin/bash

コマンド例

# 既存のPodでコマンドを実行(複数コンテナがある場合)
kubectl exec my-pod -c my-container -- ls /

# kubectl exec -it [pod name] [command]
kubectl exec -it sample_pod /bin/sh

https://www.kimullaa.com/posts/202002190914/

4)kubectl create

* ファイルまたは標準出力から、1つ以上のリソースを作成

構文

kubectl create -f FILENAME [flags]

# --dry-run=client/server(例3参照)

例1:Deploymentの作成

kubectl create deployment hello-world --image=xxxxx/xxxxx

例2:Namespaceの作成

# Step1: Namespace「kafka」を作成
kubectl create namespace kafka

# 確認
kubectl get namespace

例3:ドライランを利用し、YAMLファイルを出力

# --dry-run=client/server
kubectl create namespace demo-ns  --dry-run=client -o yaml > test.yaml

5)kubectl expose

* ReplicationController、Service、Podを
 新しいKubernetesサービスとして公開

構文

kubectl expose (-f FILENAME | TYPE NAME | TYPE/NAME) [--port=port] [--protocol=TCP|UDP] [--target-port=number-or-name] [--name=name] [--external-ip=external-ip-of-service] [--type=type] [flags]

コマンド例

kubectl expose deployment hello-world --port=80 --type=NodePort

6)kubectl port-forward

* 1つ以上のローカルポートを、Podに転送

構文

kubectl port-forward POD [LOCAL_PORT:]REMOTE_PORT [...[LOCAL_PORT_N:]REMOTE_PORT_N] [flags]

コマンド例

kubectl port-forward service/nginx-3zyl82du 8080:80

7)kubectl proxy

* Kubernetes API サーバへのプロキシを起動する

https://jamesdefabia.github.io/docs/user-guide/kubectl/kubectl_proxy/

コマンド例

kubectl proxy

# バックグラウンドで起動
kubectl proxy --port=8080 &

8)kubectl wait

* リソースの状態が指定した状態になるのを待機

https://kubernetes.io/docs/reference/generated/kubectl/kubectl-commands#wait

コマンド例

kubectl wait --timeout=90s --for=condition=available deployment/name-of-deployment

https://tech-blog.cloud-config.jp/2023-01-18-Lets-wait-for-various-things-with-kubectl-wait
https://ascii.jp/elem/000/004/126/4126561/

9)kubectl delete

* オブジェクトを削除する

https://jamesdefabia.github.io/docs/user-guide/kubectl/kubectl_delete/

コマンド例

# サービス「hello-world」を削除する
kubectl delete services hello-world

# デプロイメント全体と、そのデプロイメントに対して実行中のすべてのポッド・レプリカを削除する
kubectl delete deployment hello-world

# Delete a pod using the type and name specified in pod.json.
kubectl delete -f ./pod.json

# kubectl delete --raw <URI>
# => kubeconfig ファイルの認証情報を使った apiserver への DELETE メソッドでのアクセス

10)kubectl replace

* リソースを置き換える

https://jamesdefabia.github.io/docs/user-guide/kubectl/kubectl_replace/
https://www.mankier.com/1/kubectl-replace

コマンド例

# kubectl replace --raw "/api/v1/namespaces/<NAMESPACE>/finalize" -f ./<NAMESPACE>.json
kubectl replace --raw "/api/v1/namespaces/airflow/finalize" -f ./airflow.json

# kubectl replace --raw <URI>
# => kubeconfig ファイルの認証情報を使った apiserver への PUT メソッドでのアクセス

11)kubectl api-resources

* Kubernetesの API の resource一覧を表示する

【3】Tips

使用例1:kubernetesでnamespaceが消えない場合の対処

Terraform destroyで、EKS(K8S)で作った flink が消えなかったことを相談したら
まさに、以下の方法を教えてもらったので、メモしておく。

https://qiita.com/ishii1648/items/4f7a542d988a200eaeed

Step1:現状把握するために、ネームスペースの状態を一覧表示

$ kubectl get namespaces
NAME              STATUS        AGE
flink            Terminating   81m
# filink がTerminating のまま

Step2:ネームスペース情報をjsonファイルで出力

# kubectl get ns <NAMESPACE> -o json > <NAMESPACE(任意だが)>.json
kubectl get ns flink -o json > flink.json

Step3:jsonファイルのfinalizers部分を空にする

# flink.json
{
    ...
    "spec": {
        "finalizers": []
    },
    ...
}

Step4:kubectl replace で変更を反映

# kubectl replace --raw "/api/v1/namespaces/<NAMESPACE>/finalize" -f ./<NAMESPACE>.json
kubectl replace --raw "/api/v1/namespaces/flink/finalize" -f ./flink.json

Step5:確認

kubectl get namespaces
# filink がなくなっていることを確認

参考文献

https://qiita.com/superbrothers/items/e78a8a04347e57900fd9

関連記事

Kubernetes ~ 基礎知識編 ~
https://dk521123.hatenablog.com/entry/2020/04/27/224624
KubernetesWindows / 環境構築編 ~
https://dk521123.hatenablog.com/entry/2020/05/01/000000
Kubernetes ~ 入門編 ~
https://dk521123.hatenablog.com/entry/2020/05/04/013529
Kubernetes ~ 基本編 / kubeconfigファイル ~
https://dk521123.hatenablog.com/entry/2023/05/24/211803
Kubernetes ~ 基本編 / minikube ~
https://dk521123.hatenablog.com/entry/2023/05/07/214515
Amazon EKS ~ 基礎知識編 ~
https://dk521123.hatenablog.com/entry/2023/02/23/000000
Amazon EKS ~ 入門編 ~
https://dk521123.hatenablog.com/entry/2023/05/10/220241
学習用クラウドサービス ~ katacoda ~
https://dk521123.hatenablog.com/entry/2021/07/15/211044