techtsubame’s blog

備忘録であり、何が起きても責任は取りません

kubectlでのトラブルシュート(podコンテナ内)

kubernetes

kubectl

テスト用pod作成

[root@master01 k01]# cat myapp.yml
apiVersion: v1
kind: Pod
metadata:
  name: myapp
  labels:
    app: myapp
spec:
  containers:
  - name: hello-server
    image: blux2/hello-server:1.0
    ports:
    - containerPort: 8080

[root@master01 k01]# cat myapp3.yml
apiVersion: v1
kind: Pod
metadata:
  name: myapp3
  namespace: default
  labels:
    app: myapp
spec:
  containers:
  - name: hello-server
    image: blux2/hello-server:1.0
    ports:
    - containerPort: 8080

[root@master01 k01]#
[root@master01 k01]#
[root@master01 k01]# cat myapp.yml
apiVersion: v1
kind: Pod
metadata:
  name: myapp
  labels:
    app: myapp
spec:
  containers:
  - name: hello-server
    image: blux2/hello-server:1.0
    ports:
    - containerPort: 8080

[root@master01 k01]# cat myapp3.yml
apiVersion: v1
kind: Pod
metadata:
  name: myapp3
  namespace: default
  labels:
    app: myapp
spec:
  containers:
  - name: hello-server
    image: blux2/hello-server:1.0
    ports:
    - containerPort: 8080
[root@master01 k01]# kubectl apply --filename ./myapp.yml
pod/myapp created
[root@master01 k01]# kubectl apply --filename ./myapp3.yml
pod/myapp3 created
[root@master01 k01]#

デバッグ

  • kubectl: Kubernetesクラスタを管理するためのコマンドラインツールです。
  • debug: デバッグシェルをアタッチするサブコマンドです。
    • --stdin: デバッグシェルに標準入力を渡すオプションです。
    • --tty: デバッグシェルにTTY(端末)を割り当てるオプションです。
    • --image=curlimages/curl:8.4.0: デバッグコンテナとして使用するイメージを指定します。この例では、curlコマンドを実行するためのイメージを使用します。
    • --target=hello-server: デバッグ対象のプロセスを指定します。この例では、"hello-server"というプロセスをターゲットにします。
    • --namespace default: デバッグ対象のPodが存在する名前空間を指定します。
    • -- sh: デバッグシェルとしてshを使用することを指定します。
[root@master01 k01]# kubectl debug --stdin --tty myapp --image=curlimages/curl:8.4.0 --target=hello-server --namespace default -- sh
Targeting container "hello-server". If you don't see processes from this container it may be because the container runtime doesn't support this feature.
Defaulting debug container name to debugger-s89b4.
If you don't see a command prompt, try pressing enter.
~ $ curl localhost:8080
Hello, world!~ $
~ $ exit
Session ended, the ephemeral container will not be restarted but may be reattached using 'kubectl attach myapp -c debugger-s89b4 -i -t' if it is still running
[root@master01 k01]# 

kubectlでのトラブルシュート(pod)

kubernetes

kubectl

podのステータス

ステータス 詳細
Running 少なくとも一つのコンテナが実行中
Pending 一つ以上のコンテナが準備中
Completed 全てのコンテナが完了した状態
Unknown 何らかの理由でPodの状態が取得不可
ErrImagePull Imageの取得の失敗
Error コンテナが異常
OOMKilled OOMでコンテナが終了
Terminating Podが削除中

podのステータス確認1

[root@master01 k01]# kubectl get pod --namespace default
NAME     READY   STATUS    RESTARTS   AGE
nginx    1/1     Running   0          96m
nginx2   1/1     Running   0          4s
[root@master01 k01]#
[root@master01 k01]# kubectl get pod nginx --v=1
NAME    READY   STATUS    RESTARTS   AGE
nginx   1/1     Running   0          117m
[root@master01 k01]# kubectl get pod nginx --v=2
NAME    READY   STATUS    RESTARTS   AGE
nginx   1/1     Running   0          117m
[root@master01 k01]# kubectl get pod nginx --v=3
NAME    READY   STATUS    RESTARTS   AGE
nginx   1/1     Running   0          117m
[root@master01 k01]# kubectl get pod nginx --v=4
NAME    READY   STATUS    RESTARTS   AGE
nginx   1/1     Running   0          117m
[root@master01 k01]# kubectl get pod nginx --v=5
NAME    READY   STATUS    RESTARTS   AGE
nginx   1/1     Running   0          117m
[root@master01 k01]# kubectl get pod nginx --v=6
I0816 14:11:21.353299  120633 loader.go:395] Config loaded from file:  /root/.kube/config
I0816 14:11:21.363034  120633 round_trippers.go:553] GET https://127.0.0.1:39827/api/v1/namespaces/default/pods/nginx 200 OK in 7 milliseconds
NAME    READY   STATUS    RESTARTS   AGE
nginx   1/1     Running   0          117m
[root@master01 k01]# kubectl get pod nginx --v=7
I0816 14:11:22.333753  120640 loader.go:395] Config loaded from file:  /root/.kube/config
I0816 14:11:22.336979  120640 round_trippers.go:463] GET https://127.0.0.1:39827/api/v1/namespaces/default/pods/nginx
I0816 14:11:22.336999  120640 round_trippers.go:469] Request Headers:
I0816 14:11:22.337011  120640 round_trippers.go:473]     Accept: application/json;as=Table;v=v1;g=meta.k8s.io,application/json;as=Table;v=v1beta1;g=meta.k8s.io,application/json
I0816 14:11:22.337017  120640 round_trippers.go:473]     User-Agent: kubectl/v1.31.0 (linux/amd64) kubernetes/9edcffc
I0816 14:11:22.343724  120640 round_trippers.go:574] Response Status: 200 OK in 6 milliseconds
NAME    READY   STATUS    RESTARTS   AGE
nginx   1/1     Running   0          117m
[root@master01 k01]# kubectl get pod nginx --v=8
I0816 14:11:23.247594  120647 loader.go:395] Config loaded from file:  /root/.kube/config
I0816 14:11:23.250913  120647 round_trippers.go:463] GET https://127.0.0.1:39827/api/v1/namespaces/default/pods/nginx
I0816 14:11:23.250930  120647 round_trippers.go:469] Request Headers:
I0816 14:11:23.250939  120647 round_trippers.go:473]     Accept: application/json;as=Table;v=v1;g=meta.k8s.io,application/json;as=Table;v=v1beta1;g=meta.k8s.io,application/json
I0816 14:11:23.250946  120647 round_trippers.go:473]     User-Agent: kubectl/v1.31.0 (linux/amd64) kubernetes/9edcffc
I0816 14:11:23.257895  120647 round_trippers.go:574] Response Status: 200 OK in 6 milliseconds
I0816 14:11:23.257917  120647 round_trippers.go:577] Response Headers:
I0816 14:11:23.257927  120647 round_trippers.go:580]     Audit-Id: a4dedb0b-e8eb-4e8a-a753-0ffca2e80c4d
I0816 14:11:23.257932  120647 round_trippers.go:580]     Cache-Control: no-cache, private
I0816 14:11:23.257936  120647 round_trippers.go:580]     Content-Type: application/json
I0816 14:11:23.257939  120647 round_trippers.go:580]     X-Kubernetes-Pf-Flowschema-Uid: 9b751f1c-0dfe-4ea1-a019-30aba2da832b
I0816 14:11:23.257942  120647 round_trippers.go:580]     X-Kubernetes-Pf-Prioritylevel-Uid: b058e4ca-1e97-406b-87e0-58633b05dd0a
I0816 14:11:23.257947  120647 round_trippers.go:580]     Date: Fri, 16 Aug 2024 05:11:23 GMT
I0816 14:11:23.258047  120647 request.go:1351] Response Body: {"kind":"Table","apiVersion":"meta.k8s.io/v1","metadata":{"resourceVersion":"116897"},"columnDefinitions":[{"name":"Name","type":"string","format":"name","description":"Name must be unique within a namespace. Is required when creating resources, although some resources may allow a client to request the generation of an appropriate name automatically. Name is primarily intended for creation idempotence and configuration definition. Cannot be updated. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#names","priority":0},{"name":"Ready","type":"string","format":"","description":"The aggregate readiness state of this pod for accepting traffic.","priority":0},{"name":"Status","type":"string","format":"","description":"The aggregate status of the containers in this pod.","priority":0},{"name":"Restarts","type":"string","format":"","description":"The number of times the containers in this pod have been restarted and when the last container in this pod has restarted.","priority":0},{ [truncated 4353 chars]
NAME    READY   STATUS    RESTARTS   AGE
nginx   1/1     Running   0          117m
[root@master01 k01]# kubectl get pod nginx --v=9
I0816 14:11:24.275572  120653 loader.go:395] Config loaded from file:  /root/.kube/config
I0816 14:11:24.278116  120653 round_trippers.go:466] curl -v -XGET  -H "Accept: application/json;as=Table;v=v1;g=meta.k8s.io,application/json;as=Table;v=v1beta1;g=meta.k8s.io,application/json" -H "User-Agent: kubectl/v1.31.0 (linux/amd64) kubernetes/9edcffc" 'https://127.0.0.1:39827/api/v1/namespaces/default/pods/nginx'
I0816 14:11:24.278327  120653 round_trippers.go:510] HTTP Trace: Dial to tcp:127.0.0.1:39827 succeed
I0816 14:11:24.284851  120653 round_trippers.go:553] GET https://127.0.0.1:39827/api/v1/namespaces/default/pods/nginx 200 OK in 6 milliseconds
I0816 14:11:24.284878  120653 round_trippers.go:570] HTTP Statistics: DNSLookup 0 ms Dial 0 ms TLSHandshake 4 ms ServerProcessing 1 ms Duration 6 ms
I0816 14:11:24.284887  120653 round_trippers.go:577] Response Headers:
I0816 14:11:24.284895  120653 round_trippers.go:580]     Content-Type: application/json
I0816 14:11:24.284899  120653 round_trippers.go:580]     X-Kubernetes-Pf-Flowschema-Uid: 9b751f1c-0dfe-4ea1-a019-30aba2da832b
I0816 14:11:24.284903  120653 round_trippers.go:580]     X-Kubernetes-Pf-Prioritylevel-Uid: b058e4ca-1e97-406b-87e0-58633b05dd0a
I0816 14:11:24.284908  120653 round_trippers.go:580]     Date: Fri, 16 Aug 2024 05:11:24 GMT
I0816 14:11:24.284913  120653 round_trippers.go:580]     Audit-Id: 2c0dcd89-ecf0-4e00-856d-bfdf7819409e
I0816 14:11:24.284916  120653 round_trippers.go:580]     Cache-Control: no-cache, private
I0816 14:11:24.285026  120653 request.go:1351] Response Body: {"kind":"Table","apiVersion":"meta.k8s.io/v1","metadata":{"resourceVersion":"116897"},"columnDefinitions":[{"name":"Name","type":"string","format":"name","description":"Name must be unique within a namespace. Is required when creating resources, although some resources may allow a client to request the generation of an appropriate name automatically. Name is primarily intended for creation idempotence and configuration definition. Cannot be updated. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#names","priority":0},{"name":"Ready","type":"string","format":"","description":"The aggregate readiness state of this pod for accepting traffic.","priority":0},{"name":"Status","type":"string","format":"","description":"The aggregate status of the containers in this pod.","priority":0},{"name":"Restarts","type":"string","format":"","description":"The number of times the containers in this pod have been restarted and when the last container in this pod has restarted.","priority":0},{"name":"Age","type":"string","format":"","description":"CreationTimestamp is a timestamp representing the server time when this object was created. It is not guaranteed to be set in happens-before order across separate operations. Clients may not set this value. It is represented in RFC3339 form and is in UTC.\n\nPopulated by the system. Read-only. Null for lists. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata","priority":0},{"name":"IP","type":"string","format":"","description":"podIP address allocated to the pod. Routable at least within the cluster. Empty if not yet allocated.","priority":1},{"name":"Node","type":"string","format":"","description":"NodeName indicates in which node this pod is scheduled. If empty, this pod is a candidate for scheduling by the scheduler defined in schedulerName. Once this field is set, the kubelet for this node becomes responsible for the lifecycle of this pod. This field should not be used to express a desire for the pod to be scheduled on a specific node. https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/#nodename","priority":1},{"name":"Nominated Node","type":"string","format":"","description":"nominatedNodeName is set only when this pod preempts other pods on the node, but it cannot be scheduled right away as preemption victims receive their graceful termination periods. This field does not guarantee that the pod will be scheduled on this node. Scheduler may decide to place the pod elsewhere if other nodes become available sooner. Scheduler may also decide to give the resources on this node to a higher priority pod that is created after preemption. As a result, this field may be different than PodSpec.nodeName when the pod is scheduled.","priority":1},{"name":"Readiness Gates","type":"string","format":"","description":"If specified, all readiness gates will be evaluated for pod readiness. A pod is ready when all its containers are ready AND all conditions specified in the readiness gates have status equal to \"True\" More info: https://git.k8s.io/enhancements/keps/sig-network/580-pod-readiness-gates","priority":1}],"rows":[{"cells":["nginx","1/1","Running","0","117m","10.244.0.5","kind-control-plane","\u003cnone\u003e","\u003cnone\u003e"],"object":{"kind":"PartialObjectMetadata","apiVersion":"meta.k8s.io/v1","metadata":{"name":"nginx","namespace":"default","uid":"6643a98e-4c9b-4b89-a7c5-b3001ec80697","resourceVersion":"116897","creationTimestamp":"2024-08-16T03:13:30Z","annotations":{"kubectl.kubernetes.io/last-applied-configuration":"{\"apiVersion\":\"v1\",\"kind\":\"Pod\",\"metadata\":{\"annotations\":{},\"name\":\"nginx\",\"namespace\":\"default\"},\"spec\":{\"containers\":[{\"image\":\"nginx:1.25.3\",\"name\":\"nginx\",\"ports\":[{\"containerPort\":80}]}]}}\n"},"managedFields":[{"manager":"kubectl-client-side-apply","operation":"Update","apiVersion":"v1","time":"2024-08-16T03:13:30Z","fieldsType":"FieldsV1","fieldsV1":{"f:metadata":{"f:annotations":{".":{},"f:kubectl.kubernetes.io/last-applied-configuration":{}}},"f:spec":{"f:containers":{"k:{\"name\":\"nginx\"}":{".":{},"f:image":{},"f:imagePullPolicy":{},"f:name":{},"f:ports":{".":{},"k:{\"containerPort\":80,\"protocol\":\"TCP\"}":{".":{},"f:containerPort":{},"f:protocol":{}}},"f:resources":{},"f:terminationMessagePath":{},"f:terminationMessagePolicy":{}}},"f:dnsPolicy":{},"f:enableServiceLinks":{},"f:restartPolicy":{},"f:schedulerName":{},"f:securityContext":{},"f:terminationGracePeriodSeconds":{}}}},{"manager":"kubelet","operation":"Update","apiVersion":"v1","time":"2024-08-16T03:13:37Z","fieldsType":"FieldsV1","fieldsV1":{"f:status":{"f:conditions":{"k:{\"type\":\"ContainersReady\"}":{".":{},"f:lastProbeTime":{},"f:lastTransitionTime":{},"f:status":{},"f:type":{}},"k:{\"type\":\"Initialized\"}":{".":{},"f:lastProbeTime":{},"f:lastTransitionTime":{},"f:status":{},"f:type":{}},"k:{\"type\":\"PodReadyToStartContainers\"}":{".":{},"f:lastProbeTime":{},"f:lastTransitionTime":{},"f:status":{},"f:type":{}},"k:{\"type\":\"Ready\"}":{".":{},"f:lastProbeTime":{},"f:lastTransitionTime":{},"f:status":{},"f:type":{}}},"f:containerStatuses":{},"f:hostIP":{},"f:hostIPs":{},"f:phase":{},"f:podIP":{},"f:podIPs":{".":{},"k:{\"ip\":\"10.244.0.5\"}":{".":{},"f:ip":{}}},"f:startTime":{}}},"subresource":"status"}]}}}]}
NAME    READY   STATUS    RESTARTS   AGE
nginx   1/1     Running   0          117m
[root@master01 k01]#
[root@master01 k01]# kubectl get pod --namespace default  --output wide
NAME     READY   STATUS    RESTARTS   AGE   IP           NODE                 NOMINATED NODE   READINESS GATES
nginx    1/1     Running   0          97m   10.244.0.5   kind-control-plane   <none>           <none>
nginx2   1/1     Running   0          37s   10.244.0.6   kind-control-plane   <none>           <none>
[root@master01 k01]#

podのステータス確認2

[root@master01 k01]# kubectl get pod --namespace default --output yaml
apiVersion: v1
items:
- apiVersion: v1
  kind: Pod
  metadata:
    annotations:
      kubectl.kubernetes.io/last-applied-configuration: |
        {"apiVersion":"v1","kind":"Pod","metadata":{"annotations":{},"name":"nginx","namespace":"default"},"spec":{"containers":[{"image":"nginx:1.25.3","name":"nginx","ports":[{"containerPort":80}]}]}}
    creationTimestamp: "2024-08-16T03:13:30Z"
    name: nginx
    namespace: default
    resourceVersion: "116897"
    uid: 6643a98e-4c9b-4b89-a7c5-b3001ec80697
  spec:
    containers:
    - image: nginx:1.25.3
      imagePullPolicy: IfNotPresent
      name: nginx
      ports:
      - containerPort: 80
        protocol: TCP
      resources: {}
      terminationMessagePath: /dev/termination-log
      terminationMessagePolicy: File
      volumeMounts:
      - mountPath: /var/run/secrets/kubernetes.io/serviceaccount
        name: kube-api-access-jd7g2
        readOnly: true
    dnsPolicy: ClusterFirst
    enableServiceLinks: true
    nodeName: kind-control-plane
    preemptionPolicy: PreemptLowerPriority
    priority: 0
    restartPolicy: Always
    schedulerName: default-scheduler
    securityContext: {}
    serviceAccount: default
    serviceAccountName: default
    terminationGracePeriodSeconds: 30
    tolerations:
    - effect: NoExecute
      key: node.kubernetes.io/not-ready
      operator: Exists
      tolerationSeconds: 300
    - effect: NoExecute
      key: node.kubernetes.io/unreachable
      operator: Exists
      tolerationSeconds: 300
    volumes:
    - name: kube-api-access-jd7g2
      projected:
        defaultMode: 420
        sources:
        - serviceAccountToken:
            expirationSeconds: 3607
            path: token
        - configMap:
            items:
            - key: ca.crt
              path: ca.crt
            name: kube-root-ca.crt
        - downwardAPI:
            items:
            - fieldRef:
                apiVersion: v1
                fieldPath: metadata.namespace
              path: namespace
  status:
    conditions:
    - lastProbeTime: null
      lastTransitionTime: "2024-08-16T03:13:37Z"
      status: "True"
      type: PodReadyToStartContainers
    - lastProbeTime: null
      lastTransitionTime: "2024-08-16T03:13:30Z"
      status: "True"
      type: Initialized
    - lastProbeTime: null
      lastTransitionTime: "2024-08-16T03:13:37Z"
      status: "True"
      type: Ready
    - lastProbeTime: null
      lastTransitionTime: "2024-08-16T03:13:37Z"
      status: "True"
      type: ContainersReady
    - lastProbeTime: null
      lastTransitionTime: "2024-08-16T03:13:30Z"
      status: "True"
      type: PodScheduled
    containerStatuses:
    - containerID: containerd://6a43dec33cd468afc3f5a37256dc43665955581aff437349b6588302857e6ff6
      image: docker.io/library/nginx:1.25.3
      imageID: docker.io/library/nginx@sha256:c7a6ad68be85142c7fe1089e48faa1e7c7166a194caa9180ddea66345876b9d2
      lastState: {}
      name: nginx
      ready: true
      restartCount: 0
      started: true
      state:
        running:
          startedAt: "2024-08-16T03:13:37Z"
      volumeMounts:
      - mountPath: /var/run/secrets/kubernetes.io/serviceaccount
        name: kube-api-access-jd7g2
        readOnly: true
        recursiveReadOnly: Disabled
    hostIP: 172.18.0.2
    hostIPs:
    - ip: 172.18.0.2
    phase: Running
    podIP: 10.244.0.5
    podIPs:
    - ip: 10.244.0.5
    qosClass: BestEffort
    startTime: "2024-08-16T03:13:30Z"
- apiVersion: v1
  kind: Pod
  metadata:
    annotations:
      kubectl.kubernetes.io/last-applied-configuration: |
        {"apiVersion":"v1","kind":"Pod","metadata":{"annotations":{},"name":"nginx2","namespace":"default"},"spec":{"containers":[{"image":"nginx:1.25.3","name":"nginx","ports":[{"containerPort":80}]}]}}
    creationTimestamp: "2024-08-16T04:49:58Z"
    name: nginx2
    namespace: default
    resourceVersion: "124409"
    uid: 609f1936-e11b-4942-af53-1ec6c3d2504b
  spec:
    containers:
    - image: nginx:1.25.3
      imagePullPolicy: IfNotPresent
      name: nginx
      ports:
      - containerPort: 80
        protocol: TCP
      resources: {}
      terminationMessagePath: /dev/termination-log
      terminationMessagePolicy: File
      volumeMounts:
      - mountPath: /var/run/secrets/kubernetes.io/serviceaccount
        name: kube-api-access-xktnm
        readOnly: true
    dnsPolicy: ClusterFirst
    enableServiceLinks: true
    nodeName: kind-control-plane
    preemptionPolicy: PreemptLowerPriority
    priority: 0
    restartPolicy: Always
    schedulerName: default-scheduler
    securityContext: {}
    serviceAccount: default
    serviceAccountName: default
    terminationGracePeriodSeconds: 30
    tolerations:
    - effect: NoExecute
      key: node.kubernetes.io/not-ready
      operator: Exists
      tolerationSeconds: 300
    - effect: NoExecute
      key: node.kubernetes.io/unreachable
      operator: Exists
      tolerationSeconds: 300
    volumes:
    - name: kube-api-access-xktnm
      projected:
        defaultMode: 420
        sources:
        - serviceAccountToken:
            expirationSeconds: 3607
            path: token
        - configMap:
            items:
            - key: ca.crt
              path: ca.crt
            name: kube-root-ca.crt
        - downwardAPI:
            items:
            - fieldRef:
                apiVersion: v1
                fieldPath: metadata.namespace
              path: namespace
  status:
    conditions:
    - lastProbeTime: null
      lastTransitionTime: "2024-08-16T04:49:59Z"
      status: "True"
      type: PodReadyToStartContainers
    - lastProbeTime: null
      lastTransitionTime: "2024-08-16T04:49:58Z"
      status: "True"
      type: Initialized
    - lastProbeTime: null
      lastTransitionTime: "2024-08-16T04:49:59Z"
      status: "True"
      type: Ready
    - lastProbeTime: null
      lastTransitionTime: "2024-08-16T04:49:59Z"
      status: "True"
      type: ContainersReady
    - lastProbeTime: null
      lastTransitionTime: "2024-08-16T04:49:58Z"
      status: "True"
      type: PodScheduled
    containerStatuses:
    - containerID: containerd://0908287fe2399fe55f6f26c7cefeee7a49a81ad38f571212e7d2db2017bea1fe
      image: docker.io/library/nginx:1.25.3
      imageID: docker.io/library/nginx@sha256:c7a6ad68be85142c7fe1089e48faa1e7c7166a194caa9180ddea66345876b9d2
      lastState: {}
      name: nginx
      ready: true
      restartCount: 0
      started: true
      state:
        running:
          startedAt: "2024-08-16T04:49:59Z"
      volumeMounts:
      - mountPath: /var/run/secrets/kubernetes.io/serviceaccount
        name: kube-api-access-xktnm
        readOnly: true
        recursiveReadOnly: Disabled
    hostIP: 172.18.0.2
    hostIPs:
    - ip: 172.18.0.2
    phase: Running
    podIP: 10.244.0.6
    podIPs:
    - ip: 10.244.0.6
    qosClass: BestEffort
    startTime: "2024-08-16T04:49:58Z"
kind: List
metadata:
  resourceVersion: ""
[root@master01 k01]#

podのステータス確認3

[root@master01 k01]# kubectl get pod nginx --output json  --namespace default
{
    "apiVersion": "v1",
    "kind": "Pod",
    "metadata": {
        "annotations": {
            "kubectl.kubernetes.io/last-applied-configuration": "{\"apiVersion\":\"v1\",\"kind\":\"Pod\",\"metadata\":{\"annotations\":{},\"name\":\"nginx\",\"namespace\":\"default\"},\"spec\":{\"containers\":[{\"image\":\"nginx:1.25.3\",\"name\":\"nginx\",\"ports\":[{\"containerPort\":80}]}]}}\n"
        },
        "creationTimestamp": "2024-08-16T03:13:30Z",
        "name": "nginx",
        "namespace": "default",
        "resourceVersion": "116897",
        "uid": "6643a98e-4c9b-4b89-a7c5-b3001ec80697"
    },
    "spec": {
        "containers": [
            {
                "image": "nginx:1.25.3",
                "imagePullPolicy": "IfNotPresent",
                "name": "nginx",
                "ports": [
                    {
                        "containerPort": 80,
                        "protocol": "TCP"
                    }
                ],
                "resources": {},
                "terminationMessagePath": "/dev/termination-log",
                "terminationMessagePolicy": "File",
                "volumeMounts": [
                    {
                        "mountPath": "/var/run/secrets/kubernetes.io/serviceaccount",
                        "name": "kube-api-access-jd7g2",
                        "readOnly": true
                    }
                ]
            }
        ],
        "dnsPolicy": "ClusterFirst",
        "enableServiceLinks": true,
        "nodeName": "kind-control-plane",
        "preemptionPolicy": "PreemptLowerPriority",
        "priority": 0,
        "restartPolicy": "Always",
        "schedulerName": "default-scheduler",
        "securityContext": {},
        "serviceAccount": "default",
        "serviceAccountName": "default",
        "terminationGracePeriodSeconds": 30,
        "tolerations": [
            {
                "effect": "NoExecute",
                "key": "node.kubernetes.io/not-ready",
                "operator": "Exists",
                "tolerationSeconds": 300
            },
            {
                "effect": "NoExecute",
                "key": "node.kubernetes.io/unreachable",
                "operator": "Exists",
                "tolerationSeconds": 300
            }
        ],
        "volumes": [
            {
                "name": "kube-api-access-jd7g2",
                "projected": {
                    "defaultMode": 420,
                    "sources": [
                        {
                            "serviceAccountToken": {
                                "expirationSeconds": 3607,
                                "path": "token"
                            }
                        },
                        {
                            "configMap": {
                                "items": [
                                    {
                                        "key": "ca.crt",
                                        "path": "ca.crt"
                                    }
                                ],
                                "name": "kube-root-ca.crt"
                            }
                        },
                        {
                            "downwardAPI": {
                                "items": [
                                    {
                                        "fieldRef": {
                                            "apiVersion": "v1",
                                            "fieldPath": "metadata.namespace"
                                        },
                                        "path": "namespace"
                                    }
                                ]
                            }
                        }
                    ]
                }
            }
        ]
    },
    "status": {
        "conditions": [
            {
                "lastProbeTime": null,
                "lastTransitionTime": "2024-08-16T03:13:37Z",
                "status": "True",
                "type": "PodReadyToStartContainers"
            },
            {
                "lastProbeTime": null,
                "lastTransitionTime": "2024-08-16T03:13:30Z",
                "status": "True",
                "type": "Initialized"
            },
            {
                "lastProbeTime": null,
                "lastTransitionTime": "2024-08-16T03:13:37Z",
                "status": "True",
                "type": "Ready"
            },
            {
                "lastProbeTime": null,
                "lastTransitionTime": "2024-08-16T03:13:37Z",
                "status": "True",
                "type": "ContainersReady"
            },
            {
                "lastProbeTime": null,
                "lastTransitionTime": "2024-08-16T03:13:30Z",
                "status": "True",
                "type": "PodScheduled"
            }
        ],
        "containerStatuses": [
            {
                "containerID": "containerd://6a43dec33cd468afc3f5a37256dc43665955581aff437349b6588302857e6ff6",
                "image": "docker.io/library/nginx:1.25.3",
                "imageID": "docker.io/library/nginx@sha256:c7a6ad68be85142c7fe1089e48faa1e7c7166a194caa9180ddea66345876b9d2",
                "lastState": {},
                "name": "nginx",
                "ready": true,
                "restartCount": 0,
                "started": true,
                "state": {
                    "running": {
                        "startedAt": "2024-08-16T03:13:37Z"
                    }
                },
                "volumeMounts": [
                    {
                        "mountPath": "/var/run/secrets/kubernetes.io/serviceaccount",
                        "name": "kube-api-access-jd7g2",
                        "readOnly": true,
                        "recursiveReadOnly": "Disabled"
                    }
                ]
            }
        ],
        "hostIP": "172.18.0.2",
        "hostIPs": [
            {
                "ip": "172.18.0.2"
            }
        ],
        "phase": "Running",
        "podIP": "10.244.0.5",
        "podIPs": [
            {
                "ip": "10.244.0.5"
            }
        ],
        "qosClass": "BestEffort",
        "startTime": "2024-08-16T03:13:30Z"
    }
}
[root@master01 k01]#

podのステータス確認4

[root@master01 k01]# kubectl get pod nginx --output jsonpath='{.spec}' --namespace default | jq
{
  "containers": [
    {
      "image": "nginx:1.25.3",
      "imagePullPolicy": "IfNotPresent",
      "name": "nginx",
      "ports": [
        {
          "containerPort": 80,
          "protocol": "TCP"
        }
      ],
      "resources": {},
      "terminationMessagePath": "/dev/termination-log",
      "terminationMessagePolicy": "File",
      "volumeMounts": [
        {
          "mountPath": "/var/run/secrets/kubernetes.io/serviceaccount",
          "name": "kube-api-access-jd7g2",
          "readOnly": true
        }
      ]
    }
  ],
  "dnsPolicy": "ClusterFirst",
  "enableServiceLinks": true,
  "nodeName": "kind-control-plane",
  "preemptionPolicy": "PreemptLowerPriority",
  "priority": 0,
  "restartPolicy": "Always",
  "schedulerName": "default-scheduler",
  "securityContext": {},
  "serviceAccount": "default",
  "serviceAccountName": "default",
  "terminationGracePeriodSeconds": 30,
  "tolerations": [
    {
      "effect": "NoExecute",
      "key": "node.kubernetes.io/not-ready",
      "operator": "Exists",
      "tolerationSeconds": 300
    },
    {
      "effect": "NoExecute",
      "key": "node.kubernetes.io/unreachable",
      "operator": "Exists",
      "tolerationSeconds": 300
    }
  ],
  "volumes": [
    {
      "name": "kube-api-access-jd7g2",
      "projected": {
        "defaultMode": 420,
        "sources": [
          {
            "serviceAccountToken": {
              "expirationSeconds": 3607,
              "path": "token"
            }
          },
          {
            "configMap": {
              "items": [
                {
                  "key": "ca.crt",
                  "path": "ca.crt"
                }
              ],
              "name": "kube-root-ca.crt"
            }
          },
          {
            "downwardAPI": {
              "items": [
                {
                  "fieldRef": {
                    "apiVersion": "v1",
                    "fieldPath": "metadata.namespace"
                  },
                  "path": "namespace"
                }
              ]
            }
          }
        ]
      }
    }
  ]
}
[root@master01 k01]#

podのステータス確認5

[root@master01 k01]# kubectl get pod nginx --output jsonpath='{.spec.containers[]}' --namespace default | jq
{
  "image": "nginx:1.25.3",
  "imagePullPolicy": "IfNotPresent",
  "name": "nginx",
  "ports": [
    {
      "containerPort": 80,
      "protocol": "TCP"
    }
  ],
  "resources": {},
  "terminationMessagePath": "/dev/termination-log",
  "terminationMessagePolicy": "File",
  "volumeMounts": [
    {
      "mountPath": "/var/run/secrets/kubernetes.io/serviceaccount",
      "name": "kube-api-access-jd7g2",
      "readOnly": true
    }
  ]
}
[root@master01 k01]# 

podのステータス確認6

[root@master01 k01]# kubectl get pod nginx --output jsonpath='{.spec.containers[].image}' --namespace default
nginx:1.25.3[root@master01 k01]#

podのdescribe

[root@master01 k01]# kubectl describe pod nginx --namespace default
Name:             nginx
Namespace:        default
Priority:         0
Service Account:  default
Node:             kind-control-plane/172.18.0.2
Start Time:       Fri, 16 Aug 2024 12:13:30 +0900
Labels:           <none>
Annotations:      <none>
Status:           Running
IP:               10.244.0.5
IPs:
  IP:  10.244.0.5
Containers:
  nginx:
    Container ID:   containerd://6a43dec33cd468afc3f5a37256dc43665955581aff437349b6588302857e6ff6
    Image:          nginx:1.25.3
    Image ID:       docker.io/library/nginx@sha256:c7a6ad68be85142c7fe1089e48faa1e7c7166a194caa9180ddea66345876b9d2
    Port:           80/TCP
    Host Port:      0/TCP
    State:          Running
      Started:      Fri, 16 Aug 2024 12:13:37 +0900
    Ready:          True
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-jd7g2 (ro)
Conditions:
  Type                        Status
  PodReadyToStartContainers   True
  Initialized                 True
  Ready                       True
  ContainersReady             True
  PodScheduled                True
Volumes:
  kube-api-access-jd7g2:
    Type:                    Projected (a volume that contains injected data from multiple sources)
    TokenExpirationSeconds:  3607
    ConfigMapName:           kube-root-ca.crt
    ConfigMapOptional:       <nil>
    DownwardAPI:             true
QoS Class:                   BestEffort
Node-Selectors:              <none>
Tolerations:                 node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
                             node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events:                      <none>
[root@master01 k01]#

podのlog

  • pod内にコンテナが複数存在する場合は--containerオプションにてコンテナを指定
[root@master01 k01]# kubectl logs nginx --namespace default
/docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration
/docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/
/docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh
10-listen-on-ipv6-by-default.sh: info: Getting the checksum of /etc/nginx/conf.d/default.conf
10-listen-on-ipv6-by-default.sh: info: Enabled listen on IPv6 in /etc/nginx/conf.d/default.conf
/docker-entrypoint.sh: Sourcing /docker-entrypoint.d/15-local-resolvers.envsh
/docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh
/docker-entrypoint.sh: Launching /docker-entrypoint.d/30-tune-worker-processes.sh
/docker-entrypoint.sh: Configuration complete; ready for start up
2024/08/16 03:13:37 [notice] 1#1: using the "epoll" event method
2024/08/16 03:13:37 [notice] 1#1: nginx/1.25.3
2024/08/16 03:13:37 [notice] 1#1: built by gcc 12.2.0 (Debian 12.2.0-14)
2024/08/16 03:13:37 [notice] 1#1: OS: Linux 4.18.0-553.16.1.el8_10.x86_64
2024/08/16 03:13:37 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 1048576:1048576
2024/08/16 03:13:37 [notice] 1#1: start worker processes
2024/08/16 03:13:37 [notice] 1#1: start worker process 35
2024/08/16 03:13:37 [notice] 1#1: start worker process 36
2024/08/16 03:13:37 [notice] 1#1: start worker process 37
2024/08/16 03:13:37 [notice] 1#1: start worker process 38
[root@master01 k01]#

kindによる

kind

状態取得

[root@master01 ~]# kubectl get nodes
NAME                 STATUS   ROLES           AGE   VERSION
kind-control-plane   Ready    control-plane   82s   v1.31.0
[root@master01 ~]#
[root@master01 ~]# kind get clusters
kind
[root@master01 ~]#

nginxのマニフェスト作成

[root@master01 k01]# cat nginx_serv.yml
apiVersion: v1
kind: Pod
metadata:
  name: nginx

spec:
  containers:
  - name: nginx
    image: nginx:1.25.3
    ports:
    - containerPort: 80
[root@master01 k01]#

アプライ

[root@master01 k01]# kubectl get pod --namespace default
No resources found in default namespace.
[root@master01 k01]#
[root@master01 k01]# kubectl apply --filename ./nginx_serv.yml --namespace default
pod/nginx created
[root@master01 k01]#
[root@master01 k01]# kubectl get pod --namespace default
NAME    READY   STATUS              RESTARTS   AGE
nginx   0/1     ContainerCreating   0          5s
[root@master01 k01]#
[root@master01 k01]# kubectl get pod --namespace default
NAME    READY   STATUS    RESTARTS   AGE
nginx   1/1     Running   0          18s
[root@master01 k01]#

kindで自動生成したクラスタ定義の中身

kind

定義ファイル

  • ~/.kube.configKubernetesの構成情報を格納するファイルである
  • clustersがクラスタ自体の設定
  • contextsがクラスタに接続すための設定

    定義ファイルの詳細

  • apiVersion: ファイルのバージョンを示します。
  • clusters: クラスタに関する情報が格納されます。
  • contexts: コンテキストに関する情報が格納されます。
    • context: コンテキストの設定情報
      • cluster: 使用するクラスタの名前
      • user: 使用するユーザーの名前
    • name: コンテキストの名前
  • current-context: 現在アクティブなコンテキストの名前
  • users: ユーザーに関する情報が格納されます。
    • user: ユーザーの設定情報
      • client-certificate-data: クライアント証明書データ (base64エンコード)
      • client-key-data: クライアントキーデータ
[root@master01 ~]# cat ~/.kube/config
apiVersion: v1
clusters:
- cluster:
    certificate-authority-data: LS0 ~ snip ~
    server: https://127.0.0.1:35111
  name: kind-kind
contexts:
- context:
    cluster: kind-kind
    user: kind-kind
  name: kind-kind
current-context: kind-kind
kind: Config
preferences: {}
users:
- name: kind-kind
  user:
    client-certificate-data: LS0 ~ snip ~
    client-key-data: LS0 ~ snip ~
[root@master01 ~]#

kind,kubectlのインストール ,クラスタの作成

参考

kind.sigs.k8s.io kubernetes.io

kind

kindは、Kubernetes in Dockerの略で、Dockerコンテナの中にKubernetesクラスタを構築するためのツールです。
kindは、Kubernetesをローカルで手軽に試したい開発者にとって、非常に便利なツールです。
Docker環境さえあれば、すぐにKubernetesクラスタを立ち上げ、Kubernetesの学習や開発を進めることが可能です。

インストール

[root@master01 k01]# [ $(uname -m) = x86_64 ] && curl -Lo ./kind https://kind.sigs.k8s.io/dl/v0.23.0/kind-linux-amd64
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    98  100    98    0     0    376      0 --:--:-- --:--:-- --:--:--   376
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
100 6381k  100 6381k    0     0  4685k      0  0:00:01  0:00:01 --:--:-- 11.6M
[root@master01 k01]# chmod +x ./kind
[root@master01 k01]# sudo mv ./kind /usr/local/bin/kind
[root@master01 k01]#
[root@master01 k01]# kind --version
kind version 0.23.0
[root@master01 k01]# 

クラスタ作成

[root@master01 k01]# kind create cluster --image=kindest/node:v1.31.0
Creating cluster "kind" ...
 ✓ Ensuring node image (kindest/node:v1.31.0) 🖼
 ✓ Preparing nodes 📦
 ✓ Writing configuration 📜
 ✓ Starting control-plane 🕹️
 ✓ Installing CNI 🔌
 ✓ Installing StorageClass 💾
Set kubectl context to "kind-kind"
You can now use your cluster with:

kubectl cluster-info --context kind-kind

Have a nice day! 👋
[root@master01 k01]#

kubectl

インストール

[root@master01 k01]#    curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"

  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   138  100   138    0     0    679      0 --:--:-- --:--:-- --:--:--   679
100 53.7M  100 53.7M    0     0  31.2M      0  0:00:01  0:00:01 --:--:-- 33.3M
[root@master01 k01]#
[root@master01 k01]# install -o root -g root -m 0755 kubectl /usr/local/bin/kubectl
[root@master01 k01]#
[root@master01 k01]# kubectl version --client
Client Version: v1.31.0
Kustomize Version: v5.4.2
[root@master01 k01]#
[root@master01 k01]# kubectl cluster-info --context kind-kind
Kubernetes control plane is running at https://127.0.0.1:35111
CoreDNS is running at https://127.0.0.1:35111/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy

To further debug and diagnose cluster problems, use 'kubectl cluster-info dump'.
[root@master01 k01]#

DockerFileからのコンテナ起動

Docker

Dockerfileの作成

[root@master01 work]# cat Dockerfile
FROM nginx:1.25.3

COPY index.html /user/share/nginx/html
[root@master01 work]# 

index.htmlの作成

[root@master01 work]# cat index.html
<h1>index.html Dockerfile<h1>
[root@master01 work]#

Build

[root@master01 work]# docker build ./ --tag nginx-custom:1.0
[+] Building 1.1s (7/7) FINISHED                                                                                                                                                                            docker:default
 => [internal] load build definition from Dockerfile                                                                                                                                                                  0.1s
 => => transferring dockerfile: 155B                                                                                                                                                                                  0.0s
 => [internal] load metadata for docker.io/library/nginx:1.25.3                                                                                                                                                       0.0s
 => [internal] load .dockerignore                                                                                                                                                                                     0.1s
 => => transferring context: 2B                                                                                                                                                                                       0.0s
 => [internal] load build context                                                                                                                                                                                     0.2s
 => => transferring context: 127B                                                                                                                                                                                     0.0s
 => [1/2] FROM docker.io/library/nginx:1.25.3                                                                                                                                                                         0.4s
 => [2/2] COPY index.html /user/share/nginx/html                                                                                                                                                                      0.1s
 => exporting to image                                                                                                                                                                                                0.1s
 => => exporting layers                                                                                                                                                                                               0.1s
 => => writing image sha256:98aea8354dc1feb718e8335ee95bacebc0a10cec3a7f01aec425ddea4e3cda5a                                                                                                                          0.0s
 => => naming to docker.io/library/nginx-custom:1.0                                                                                                                                                                   0.0s
[root@master01 work]#

run

前回起動のコンテナはstopする

[root@master01 work]# docker stop web
web
[root@master01 work]# docker ps -a
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
[root@master01 work]#
[root@master01 work]# docker run --rm --detach --publish 8080:80 --name web nginx-custom:1.0
633015f7e78046595859f23c4775bd2d9cf0f92229940af58cb3103fa096fa1d
[root@master01 work]#
[root@master01 work]# docker ps -a
CONTAINER ID   IMAGE              COMMAND                   CREATED         STATUS         PORTS                                   NAMES
633015f7e780   nginx-custom:1.0   "/docker-entrypoint.…"   5 seconds ago   Up 4 seconds   0.0.0.0:8080->80/tcp, :::8080->80/tcp   web
[root@master01 work]#

アクセス

ブラウザで http://dockerサーバ:8080 にアクセス