LoginSignup

This article is a Private article. Only a writer and users who know the URL can access it.
Please change open range to public in publish setting if you want to share this article with other users.

More than 3 years have passed since last update.

kubectlコマンド演習

Last updated at Posted at 2020-01-07

kubectlコマンドのインストール

1.kubectl(linux用)をダウンロード

コマンド
# curl -LO https://storage.googleapis.com/kubernetes-release/release/$(curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt)/bin/linux/amd64/kubectl
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 40.9M  100 40.9M    0     0  44.2M      0 --:--:-- --:--:-- --:--:-- 44.1M

2.実行権限の付与

コマンド
# chmod +x ./kubectl

3.kubectlファイルの移動

コマンド
# mv ./kubectl /usr/local/bin/kubectl

4.「.kube」ディレクトリの作成

コマンド
# mkdir .kube

8.コピーした内容を「.kube/config」ファイルを作成と同時にペースト

コマンド
# vim .kube/config
----------------------------------------------
コピーした内容をペースト
----------------------------------------------
Esc + :wq

kubectlコマンド演習

Podの作成

1.Nginxという名前のNginx Podを作成

コマンド
# kubectl run nginx --image=nginx --restart=Never
pod/nginx created

2.Nginx Podの確認

コマンド
# kubectl get pod
NAME    READY   STATUS    RESTARTS   AGE
nginx   1/1     Running   0          2m6s

3.Nginx Podの削除

コマンド
# kubectl delete pod nginx
pod "nginx" deleted

4.Nginx Podをyamlを生成して、そのyamlから作成

コマンド
# kubectl run nginx --image=nginx --restart=Never --dry-run -o yaml > nginx.yaml
コマンド
# kubectl create -f nginx.yaml
pod/nginx created
コマンド
# kubectl get pod nginx
NAME    READY   STATUS    RESTARTS   AGE
nginx   1/1     Running   0          33s

5.Nginx Podの詳細確認

コマンド
# kubectl describe pod nginx
Name:         nginx
Namespace:    default
Priority:     0
Node:         35.194.122.180/35.194.122.180
Start Time:   Mon, 08 Jul 2019 10:14:26 +0000
Labels:       run=nginx
Annotations:  cni.projectcalico.org/podIP: 10.42.0.6/32
Status:       Running
IP:           10.42.0.6
Containers:
  nginx:
    Container ID:   docker://d0e8ac24d7c0bdd303d8e7784dce10c5c3cb519109df5d57b91622452720a848
    Image:          nginx
    Image ID:       docker-pullable://nginx@sha256:96fb261b66270b900ea5a2c17a26abbfabe95506e73c3a3c65869a6dbe83223a
    Port:           <none>
    Host Port:      <none>
    State:          Running
      Started:      Mon, 08 Jul 2019 10:14:30 +0000
    Ready:          True
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-p5r8z (ro)
Conditions:
  Type              Status
  Initialized       True 
  Ready             True 
  ContainersReady   True 
  PodScheduled      True 
Volumes:
  default-token-p5r8z:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-p5r8z
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/not-ready:NoExecute for 300s
                 node.kubernetes.io/unreachable:NoExecute for 300s
Events:
  Type    Reason     Age   From                     Message
  ----    ------     ----  ----                     -------
  Normal  Scheduled  86s   default-scheduler        Successfully assigned default/nginx to 35.194.122.180
  Normal  Pulling    85s   kubelet, 35.194.122.180  pulling image "nginx"
  Normal  Pulled     82s   kubelet, 35.194.122.180  Successfully pulled image "nginx"
  Normal  Created    82s   kubelet, 35.194.122.180  Created container
  Normal  Started    82s   kubelet, 35.194.122.180  Started container

6.Nginx Podの削除

コマンド
# kubectl delete pod nginx
pod "nginx" deleted

Labelの作成

1.nginxという名前でapp=v1というラベルを持つNginx Podを作成

コマンド
# kubectl run nginx --image=nginx --restart=Never --labels=app=v1
pod/nginx created

2.すべてのPodラベル確認

コマンド
# kubectl get pod --show-labels
NAME    READY   STATUS    RESTARTS   AGE   LABELS
nginx   1/1     Running   0          62s   app=v1

3.app=v2にラベル名を変更

コマンド
# kubectl label pod nginx app=v2 --overwrite
pod/nginx labeled

4.appラベルを持つPodのみ確認

コマンド
# kubectl get pod -L app
NAME    READY   STATUS    RESTARTS   AGE     APP
nginx   1/1     Running   0          2m59s   v2

5.app=v2ラベルを持つPodのみ確認

コマンド
# kubectl get pod -l app=v2
NAME    READY   STATUS    RESTARTS   AGE
nginx   1/1     Running   0          3m48s

6.Nginx Podの削除

コマンド
# kubectl delete pod nginx
pod "nginx" deleted

Deployment作成

1.nginxという名前でバージョン1.7.8のNginx,レプリカ数2のDeploymentの作成

コマンド
# kubectl run nginx --image=nginx:1.7.8 --replicas=2
kubectl run --generator=deployment/apps.v1 is DEPRECATED and will be removed in a future version. Use kubectl run --generator=run-pod/v1 or kubectl create instead.
deployment.apps/nginx created
コマンド
# kubectl delete deployment nginx
deployment.extensions "nginx" deleted

runコマンドでDeploymentを作成することは今後のバージョンでは非推奨のため、yamlから作成

コマンド
# kubectl create deployment nginx --image=nginx:1.7.8 --dry-run -o yaml > nginx_dep.yaml

nginx_dep.yamlのreplicasを1から2へ変更

コマンド
# vim nginx_dep.yaml
----------------------------------------------------------
apiVersion: apps/v1
kind: Deployment
metadata:
  creationTimestamp: null
  labels:
    app: nginx
  name: nginx
spec:
  replicas: 2 #1から2へ変更
  selector:
    matchLabels:
      app: nginx
  strategy: {}
  template:
    metadata:
      creationTimestamp: null
      labels:
        app: nginx
    spec:
      containers:
      - image: nginx:1.7.8
        name: nginx
        resources: {}
status: {}
----------------------------------------------------------
Esc + :wq

nginx_dep.yamlからDeploymentを作成

コマンド
# kubectl create -f nginx_dep.yaml
deployment.apps/nginx created

2.Podが2個生成されていることを確認

コマンド
# kubectl get pod
NAME                     READY   STATUS    RESTARTS   AGE
nginx-85c4646787-gzp7t   1/1     Running   0          8s
nginx-85c4646787-w2nnr   1/1     Running   0          8s

3.1podを削除して、セルフヒーリングを確認

コマンド
# kubectl delete pod nginx-85c4646787-gzp7t
pod "nginx-85c4646787-gzp7t" deleted
コマンド
# kubectl get pod
NAME                     READY   STATUS    RESTARTS   AGE
nginx-85c4646787-sf5vx   1/1     Running   0          18s
nginx-85c4646787-w2nnr   1/1     Running   0          55s

4.Nginxを1.7.9にアップデート

コマンド
# kubectl set image deployment nginx nginx=nginx:1.7.9
deployment.extensions/nginx image updated
コマンド
# kubectl describe deployment nginx
Name:                   nginx
Namespace:              default
CreationTimestamp:      Tue, 09 Jul 2019 02:47:42 +0000
Labels:                 app=nginx
Annotations:            deployment.kubernetes.io/revision: 2
Selector:               app=nginx
Replicas:               2 desired | 2 updated | 2 total | 2 available | 0 unavailable
StrategyType:           RollingUpdate
MinReadySeconds:        0
RollingUpdateStrategy:  25% max unavailable, 25% max surge
Pod Template:
  Labels:  app=nginx
  Containers:
   nginx:
    Image:        nginx:1.7.9
    Port:         <none>
    Host Port:    <none>
    Environment:  <none>
    Mounts:       <none>
  Volumes:        <none>
Conditions:
  Type           Status  Reason
  ----           ------  ------
  Available      True    MinimumReplicasAvailable
  Progressing    True    NewReplicaSetAvailable
OldReplicaSets:  <none>
NewReplicaSet:   nginx-77c5cd5446 (2/2 replicas created)
Events:
  Type    Reason             Age   From                   Message
  ----    ------             ----  ----                   -------
  Normal  ScalingReplicaSet  119s  deployment-controller  Scaled up replica set nginx-85c4646787 to 2
  Normal  ScalingReplicaSet  37s   deployment-controller  Scaled up replica set nginx-77c5cd5446 to 1
  Normal  ScalingReplicaSet  35s   deployment-controller  Scaled down replica set nginx-85c4646787 to 1
  Normal  ScalingReplicaSet  35s   deployment-controller  Scaled up replica set nginx-77c5cd5446 to 2
  Normal  ScalingReplicaSet  33s   deployment-controller  Scaled down replica set nginx-85c4646787 to 0

5.Revision内容の確認

コマンド
# kubectl rollout history deployment nginx
deployment.extensions/nginx 
REVISION  CHANGE-CAUSE
1         <none>
2         <none>
コマンド
# kubectl rollout history deployment nginx --revision=1
deployment.extensions/nginx with revision #1
Pod Template:
  Labels:       app=nginx
        pod-template-hash=85c4646787
  Containers:
   nginx:
    Image:      nginx:1.7.8
    Port:       <none>
    Host Port:  <none>
    Environment:        <none>
    Mounts:     <none>
  Volumes:      <none>
コマンド
# kubectl rollout history deployment nginx --revision=2
deployment.extensions/nginx with revision #2
Pod Template:
  Labels:       app=nginx
        pod-template-hash=77c5cd5446
  Containers:
   nginx:
    Image:      nginx:1.7.9
    Port:       <none>
    Host Port:  <none>
    Environment:        <none>
    Mounts:     <none>
  Volumes:      <none>

6.Nginxのバージョンを1.7.8にロールバック

コマンド
# kubectl rollout undo deployment nginx
deployment.extensions/nginx rolled back
コマンド
# kubectl describe deployment nginx
Name:                   nginx
Namespace:              default
CreationTimestamp:      Tue, 09 Jul 2019 02:47:42 +0000
Labels:                 app=nginx
Annotations:            deployment.kubernetes.io/revision: 3
Selector:               app=nginx
Replicas:               2 desired | 2 updated | 2 total | 2 available | 0 unavailable
StrategyType:           RollingUpdate
MinReadySeconds:        0
RollingUpdateStrategy:  25% max unavailable, 25% max surge
Pod Template:
  Labels:  app=nginx
  Containers:
   nginx:
    Image:        nginx:1.7.8
    Port:         <none>
    Host Port:    <none>
    Environment:  <none>
    Mounts:       <none>
  Volumes:        <none>
Conditions:
  Type           Status  Reason
  ----           ------  ------
  Available      True    MinimumReplicasAvailable
  Progressing    True    NewReplicaSetAvailable
OldReplicaSets:  <none>
NewReplicaSet:   nginx-85c4646787 (2/2 replicas created)
Events:
  Type    Reason             Age                 From                   Message
  ----    ------             ----                ----                   -------
  Normal  ScalingReplicaSet  4m5s                deployment-controller  Scaled up replica set nginx-77c5cd5446 to 1
  Normal  ScalingReplicaSet  4m3s                deployment-controller  Scaled down replica set nginx-85c4646787 to 1
  Normal  ScalingReplicaSet  4m3s                deployment-controller  Scaled up replica set nginx-77c5cd5446 to 2
  Normal  ScalingReplicaSet  4m1s                deployment-controller  Scaled down replica set nginx-85c4646787 to 0
  Normal  ScalingReplicaSet  8s                  deployment-controller  Scaled up replica set nginx-85c4646787 to 1
  Normal  ScalingReplicaSet  6s (x2 over 5m27s)  deployment-controller  Scaled up replica set nginx-85c4646787 to 2
  Normal  ScalingReplicaSet  6s                  deployment-controller  Scaled down replica set nginx-77c5cd5446 to 1
  Normal  ScalingReplicaSet  4s                  deployment-controller  Scaled down replica set nginx-77c5cd5446 to 0

7.Nginxのバージョンを revision 2 の nginx 1.7.9 にロールバック

コマンド
# kubectl rollout undo deployment nginx --to-revision=2
deployment.extensions/nginx rolled back
コマンド
# kubectl describe deployment nginx
Name:                   nginx
Namespace:              default
CreationTimestamp:      Tue, 09 Jul 2019 02:47:42 +0000
Labels:                 app=nginx
Annotations:            deployment.kubernetes.io/revision: 4
Selector:               app=nginx
Replicas:               2 desired | 2 updated | 2 total | 2 available | 0 unavailable
StrategyType:           RollingUpdate
MinReadySeconds:        0
RollingUpdateStrategy:  25% max unavailable, 25% max surge
Pod Template:
  Labels:  app=nginx
  Containers:
   nginx:
    Image:        nginx:1.7.9
    Port:         <none>
    Host Port:    <none>
    Environment:  <none>
    Mounts:       <none>
  Volumes:        <none>
Conditions:
  Type           Status  Reason
  ----           ------  ------
  Available      True    MinimumReplicasAvailable
  Progressing    True    NewReplicaSetAvailable
OldReplicaSets:  <none>
NewReplicaSet:   nginx-77c5cd5446 (2/2 replicas created)
Events:
  Type    Reason             Age                  From                   Message
  ----    ------             ----                 ----                   -------
  Normal  ScalingReplicaSet  58s                  deployment-controller  Scaled up replica set nginx-85c4646787 to 1
  Normal  ScalingReplicaSet  56s (x2 over 6m17s)  deployment-controller  Scaled up replica set nginx-85c4646787 to 2
  Normal  ScalingReplicaSet  56s                  deployment-controller  Scaled down replica set nginx-77c5cd5446 to 1
  Normal  ScalingReplicaSet  54s                  deployment-controller  Scaled down replica set nginx-77c5cd5446 to 0
  Normal  ScalingReplicaSet  9s (x2 over 4m55s)   deployment-controller  Scaled up replica set nginx-77c5cd5446 to 1
  Normal  ScalingReplicaSet  6s (x2 over 4m53s)   deployment-controller  Scaled down replica set nginx-85c4646787 to 1
  Normal  ScalingReplicaSet  6s (x2 over 4m53s)   deployment-controller  Scaled up replica set nginx-77c5cd5446 to 2
  Normal  ScalingReplicaSet  4s (x2 over 4m51s)   deployment-controller  Scaled down replica set nginx-85c4646787 to 0

8.deploymentの削除

コマンド
# kubectl delete deployment nginx
deployment.extensions "nginx" deleted

Serviceの作成

1.nginxという名前のポッドを作成、ポート80を公開

コマンド
# kubectl run nginx --image=nginx --restart=Never --port=80 --expose
service/nginx created
pod/nginx created

2.nginx serviceとエンドポイントのIP確認

コマンド
# kubectl get service nginx
NAME    TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)   AGE
nginx   ClusterIP   10.43.107.89   <none>        80/TCP    57s
コマンド
# kubectl get ep
NAME         ENDPOINTS            AGE
kubernetes   35.200.85.217:6443   166m
nginx        10.42.0.16:80        72s

3.busybox podを作成し、busyboxコンテナーからwgetコマンドでnginx serviceを経由したアクセス確認

コマンド
# kubectl run busybox --image=busybox --restart=Never --rm -it /bin/sh
If you don't see a command prompt, try pressing enter.
/ # wget -O- 10.42.0.16
Connecting to 10.42.0.16 (10.42.0.16:80)
writing to stdout
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>
-                    100% |******************************************************************************************|   612  0:00:00 ETA
written to stdout
/ # exit
pod "busybox" deleted

4.nginx podとnginx serviceの削除

コマンド
# kubectl delete pod nginx
pod "nginx" deleted
コマンド
# kubectl delete service nginx
service "nginx" deleted

configmapの作成

1. “var1=val1” “var2=val2”のconfigMap ‘config'を作成

コマンド
# kubectl create configmap config --from-literal=var1=val1 --from-literal=var2=val2
configmap/config created
コマンド
# kubectl get configmap config
NAME     DATA   AGE
config   2      67s
コマンド
# kubectl get configmap config -o yaml
apiVersion: v1
data:
  var1: val1
  var2: val2
kind: ConfigMap
metadata:
  creationTimestamp: "2019-07-09T04:34:00Z"
  name: config
  namespace: default
  resourceVersion: "18633"
  selfLink: /api/v1/namespaces/default/configmaps/config
  uid: c5cc64ca-a202-11e9-b725-42010a92002e

2.configMap ’config’をenv変数としてnginx podにロード

コマンド
# kubectl run --restart=Never nginx --image=nginx -o yaml --dry-run > nginx_configmap.yaml
コマンド
# vim nginx_configmap.yaml
----------------------------------------------------------
apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: null
  labels:
    run: nginx
  name: nginx
spec:
  containers:
  - image: nginx
    imagePullPolicy: IfNotPresent
    name: nginx
    resources: {}
    envFrom:
    - configMapRef:
          name: config
  dnsPolicy: ClusterFirst
  restartPolicy: Never
status: {}
----------------------------------------------------------
Esc + :wq

3.Nginx Podの作成

コマンド
# kubectl create -f nginx_configmap.yaml
pod/nginx created

4.環境変数が読み込まれていることを確認 ※var1=val1 var2=val2が表示される

コマンド
# kubectl exec -it nginx -- env
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
HOSTNAME=nginx
TERM=xterm
var1=val1
var2=val2
KUBERNETES_PORT_443_TCP_PROTO=tcp
KUBERNETES_PORT_443_TCP_PORT=443
KUBERNETES_PORT_443_TCP_ADDR=10.43.0.1
KUBERNETES_SERVICE_HOST=10.43.0.1
KUBERNETES_SERVICE_PORT=443
KUBERNETES_SERVICE_PORT_HTTPS=443
KUBERNETES_PORT=tcp://10.43.0.1:443
KUBERNETES_PORT_443_TCP=tcp://10.43.0.1:443
NGINX_VERSION=1.17.1
NJS_VERSION=0.3.3
PKG_RELEASE=1~stretch
HOME=/root

5.Nginx podの削除

コマンド
# kubectl delete -f nginx_configmap.yaml
pod "nginx" deleted

Multi-container Podの作成

busyboxイメージを利用して “echo CloudNative Days Tokyo; sleep 3600”というコマンドを実行する、2つのコンテナーを内包するPodを作成します。 2番目のコンテナーに接続して「ls」を実行してみましょう。

1.busybox yamlを作成

コマンド
# kubectl run busybox --image=busybox --restart=Never -o yaml --dry-run -- /bin/sh -c 'echo CloudNative Days Tokyo;sleep 3600' > multi.yaml

2.2つ目のコンテナーを追記

コマンド
# vim multi.yaml
------------------------------------------------------
apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: null
  labels:
    run: busybox
  name: busybox
spec:
  containers:
  - args:
    - /bin/sh
    - -c
    - echo CloudNative Days Tokyo;sleep 3600
    image: busybox
    name: busybox
    resources: {}
  - args:
    - /bin/sh
    - -c
    - echo CloudNative Days Tokyo;sleep 3600
    image: busybox
    name: busybox2
  dnsPolicy: ClusterFirst
  restartPolicy: Never
status: {}
------------------------------------------------------
Esc + :wq

3.Pod作成

コマンド
# kubectl create -f multi.yaml
pod/busybox created
コマンド
# kubectl get pod
NAME      READY   STATUS    RESTARTS   AGE
busybox   2/2     Running   0          46s

4.2つ目のコンテナーにアクセス

コマンド
# kubectl exec -it busybox -c busybox2 -- /bin/sh
/ # ls
bin   dev   etc   home  proc  root  sys   tmp   usr   var
/ # exit

5.Podの削除

コマンド
# kubectl delete pod busybox
pod "busybox" deleted
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up