IT/쿠버네티스 / / 2020. 2. 2.

[kubernetes-실습] API 객체

포스팅 목차

    RESTful API Access (토큰 기반 리소스 접근,  namespace 토큰 생성)

    api server의 node의 ip와 port 확인, 클러스트 설정 정보 확인

    ps0107@k8smaster1:~$ kubectl config view
    apiVersion: v1
    clusters:
    - cluster:
        certificate-authority-data: DATA+OMITTED
        server: https://k8smaster:6443
      name: kubernetes
    contexts:
    - context:
        cluster: kubernetes
        user: kubernetes-admin
      name: kubernetes-admin@kubernetes
    current-context: kubernetes-admin@kubernetes
    kind: Config
    preferences: {}
    users:
    - name: kubernetes-admin
      user:
        client-certificate-data: REDACTED
        client-key-data: REDACTED

     

    bearer token 확인 필요

    secrets : volume 리소스 유형중 하나 (크리티컬한 정보들도 pod간 공유, 자동 인코딩 되어 저장)    

    ps0107@k8smaster1:~$ kubectl get secrets --all-namespaces
    NAMESPACE         NAME                                             TYPE                                  DATA   AGE
    default           default-token-76w5h                              kubernetes.io/service-account-token   3      5d3h
    kube-node-lease   default-token-868ws                              kubernetes.io/service-account-token   3      5d3h
    kube-public       default-token-vrv96                              kubernetes.io/service-account-token   3      5d3h
    kube-system       attachdetach-controller-token-q6gnc              kubernetes.io/service-account-token   3      5d3h
    kube-system       bootstrap-signer-token-52n72                     kubernetes.io/service-account-token   3      5d3h
    kube-system       bootstrap-token-jaeaqt                           bootstrap.kubernetes.io/token         6      5d3h
    kube-system       bootstrap-token-qa1m8y                           bootstrap.kubernetes.io/token         4      5d3h
    kube-system       calico-node-token-9d74h                          kubernetes.io/service-account-token   3      5d3h
    kube-system       certificate-controller-token-scw76               kubernetes.io/service-account-token   3      5d3h
    kube-system       clusterrole-aggregation-controller-token-bzb8m   kubernetes.io/service-account-token   3      5d3h
    kube-system       coredns-token-cmpj6                              kubernetes.io/service-account-token   3      5d3h
    kube-system       cronjob-controller-token-rdp76                   kubernetes.io/service-account-token   3      5d3h
    kube-system       daemon-set-controller-token-zrfl2                kubernetes.io/service-account-token   3      5d3h
    kube-system       default-token-9xjr8                              kubernetes.io/service-account-token   3      5d3h
    kube-system       deployment-controller-token-dghwg                kubernetes.io/service-account-token   3      5d3h
    kube-system       disruption-controller-token-s5rdz                kubernetes.io/service-account-token   3      5d3h
    kube-system       endpoint-controller-token-fk4gw                  kubernetes.io/service-account-token   3      5d3h
    kube-system       expand-controller-token-xqdz5                    kubernetes.io/service-account-token   3      5d3h
    kube-system       generic-garbage-collector-token-gg8l7            kubernetes.io/service-account-token   3      5d3h
    kube-system       horizontal-pod-autoscaler-token-5xjpz            kubernetes.io/service-account-token   3      5d3h
    kube-system       job-controller-token-ndn45                       kubernetes.io/service-account-token   3      5d3h
    kube-system       kube-proxy-token-7jjl9                           kubernetes.io/service-account-token   3      5d3h
    kube-system       kubeadm-certs                                    Opaque                                8      5d3h
    kube-system       namespace-controller-token-z7vnn                 kubernetes.io/service-account-token   3      5d3h
    kube-system       node-controller-token-jgg7f                      kubernetes.io/service-account-token   3      5d3h
    kube-system       persistent-volume-binder-token-7qksk             kubernetes.io/service-account-token   3      5d3h
    kube-system       pod-garbage-collector-token-9bgvk                kubernetes.io/service-account-token   3      5d3h
    kube-system       pv-protection-controller-token-7nbqk             kubernetes.io/service-account-token   3      5d3h
    kube-system       pvc-protection-controller-token-zssxk            kubernetes.io/service-account-token   3      5d3h
    kube-system       replicaset-controller-token-59szg                kubernetes.io/service-account-token   3      5d3h
    kube-system       replication-controller-token-5j78s               kubernetes.io/service-account-token   3      5d3h
    kube-system       resourcequota-controller-token-95qgb             kubernetes.io/service-account-token   3      5d3h
    kube-system       service-account-controller-token-d4fmk           kubernetes.io/service-account-token   3      5d3h
    kube-system       service-controller-token-wbbpt                   kubernetes.io/service-account-token   3      5d3h
    kube-system       statefulset-controller-token-hsk8b               kubernetes.io/service-account-token   3      5d3h
    kube-system       token-cleaner-token-v8r9r                        kubernetes.io/service-account-token   3      5d3h
    kube-system       ttl-controller-token-tjbl4                       kubernetes.io/service-account-token   3      5d3h
    sock-shop         default-token-fjxvf                              kubernetes.io/service-account-token   3      3d6h

     

    default namespace 인것 확인

    ps0107@k8smaster1:~$ kubectl get secrets
    NAME                  TYPE                                  DATA   AGE
    default-token-76w5h   kubernetes.io/service-account-token   3      5d3h

     

    해당 secret에 있는 token 정보 확인

    ps0107@k8smaster1:~$ kubectl describe secret default-token-76w5h
    Name:         default-token-76w5h
    Namespace:    default
    Labels:       <none>
    Annotations:  kubernetes.io/service-account.name: default
                  kubernetes.io/service-account.uid: d063e90a-2b41-43a9-88c2-9e4e3e8839c9
    
    Type:  kubernetes.io/service-account-token
    
    Data
    ====
    namespace:  7 bytes
    token:      eyJhbGciOiJSUzI1NiIsImtpZCI6IiJ9.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJkZWZhdWx0Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZWNyZXQubmFtZSI6ImRlZmF1bHQtdG9rZW4tNzZ3NWgiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC5uYW1lIjoiZGVmYXVsdCIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VydmljZS1hY2NvdW50LnVpZCI6ImQwNjNlOTBhLTJiNDEtNDNhOS04OGMyLTllNGUzZTg4MzljOSIsInN1YiI6InN5c3RlbTpzZXJ2aWNlYWNjb3VudDpkZWZhdWx0OmRlZmF1bHQifQ.lLz_lHjoBNnzTsNQR4x8r7s2saIqVCRM1emPUjio9PyNXd02zHs9l-jGQS3PnvX1FyyK1eYHYUuk6OibR5MZqHJEblz22xjI1alniVVwAAxh3r7PmoQXdbYnLUZYxqu2XKc1XkWlnDK1TQmU6zMc0oUYLjsIYjrC0FZ7l8dju3dx3rlpVA9qD7nq1obmwGHKg7ItJW2s5od1DXKJfOo3Li4P5PVmfUR-VDVCR5glPUXS_jWfQp9FmMxWKfI95b-vzjNNYI-rzbBrHWqY_DN6c9Qm2eQsHKo7r5DT8XPKLv-wyH5RD1glqMcOwM8BObsJDjfamRp9cjS37FrEIDQqkw
    ca.crt:     1025 bytes

     

    token 정보를 변수에 export하여 저장

    ps0107@k8smaster1:~$ export token=$(kubectl describe secret default-token-76w5h | grep ^token | cut -f7 -d ' ')

     

    -k 옵션은 인증없이 사용한다

    ps0107@k8smaster1:~$ curl https://k8smaster:6443/apis --header "Authorization: Bearer $token" -k
    {
      "kind": "APIGroupList",
      "apiVersion": "v1",
      "groups": [
        {
          "name": "apiregistration.k8s.io",
          "versions": [
            {
              "groupVersion": "apiregistration.k8s.io/v1",
              "version": "v1"
            },
            {
              "groupVersion": "apiregistration.k8s.io/v1beta1",
              "version": "v1beta1"
            }
          ],
          "preferredVersion": {
            "groupVersion": "apiregistration.k8s.io/v1",
            "version": "v1"
          }
        },
    .......

     

    해당 토큰은 namespace의 권한이 없기 때문에 403 에러가 발생한다.

    ps0107@k8smaster1:~$ curl https://k8smaster:6443/api/v1/namespaces --header "Authorization: Bearer $token" -k
    {
      "kind": "Status",
      "apiVersion": "v1",
      "metadata": {
    
      },
      "status": "Failure",
      "message": "namespaces is forbidden: User \"system:serviceaccount:default:default\" cannot list resource \"namespaces\" in API group \"\" at the cluster scope",
      "reason": "Forbidden",
      "details": {
        "kind": "namespaces"
      },
      "code": 403
    }

     

    namespace별 할당된 토큰이 pod가 런칭되었얼때 해당 토큰을 사용한다.
    pod의 /var/run/secrets/kubernetes.io/serviceaccount/ 경로로 마운트 된것을 볼수 있다.

    ps0107@k8smaster1:~$ kubectl run -it busybox --image=busybox --restart=Never
    If you don't see a command prompt, try pressing enter.
    / # cd /var/run/secrets/kubernetes.io/serviceaccount/
    / # ls 
    ca.crt     namespace  token
    / # cat token
    eyJhbGciOiJSUzI1NiIsImtpZCI6IiJ9.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJkZWZhdWx0Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZWNyZXQubmFtZSI6ImRlZmF1bHQtdG9rZW4tNzZ3NWgiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC5uYW1lIjoiZGVmYXVsdCIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VydmljZS1hY2NvdW50LnVpZCI6ImQwNjNlOTBhLTJiNDEtNDNhOS04OGMyLTllNGUzZTg4MzljOSIsInN1YiI6InN5c3RlbTpzZXJ2aWNlYWNjb3VudDpkZWZhdWx0OmRlZmF1bHQifQ.lLz_lHjoBNnzTsNQR4x8r7s2saIqVCRM1emPUjio9PyNXd02zHs9l-jGQS3PnvX1FyyK1eYHYUuk6OibR5MZqHJEblz22xjI1alniVVwAAxh3r7PmoQXdbYnLUZYxqu2XKc1XkWlnDK1TQmU6zMc0oUYLjsIYjrC0FZ7l8dju3dx3rlpVA9qD7nq1obmwGHKg7ItJW2s5od1DXKJfOo3Li4P5PVmfUR-VDVCR5glPUXS_jWfQp9FmMxWKfI95b-vzjNNYI-rzbBrHWqY_DN6c9Qm2eQsHKo7r5DT8XPKLv-wyH5RD1glqMcOwM8BObsJDjfamRp9cjS37FrEIDQqkw
    / # exit
    ps0107@k8smaster1:~$

     

    --restart={옵션}
    1. Always : deployment 객체로 생성
    2. Never : 단순 pod로 배포
    3. Onfailure : Job기반

     

     

     


    Proxy 사용해 보기

    proxy 도움페이지 보기

    ps0107@k8smaster1:~$ kubectl proxy -h
    Creates a proxy server or application-level gateway between localhost and the Kubernetes API Server. It also allows
    serving static content over specified HTTP path. All incoming data enters through one port and gets forwarded to the
    remote kubernetes API Server port, except for the path matching the static content path.
    
    Examples:
      # To proxy all of the kubernetes api and nothing else, use:
    
      $ kubectl proxy --api-prefix=/
    
      # To proxy only part of the kubernetes api and also some static files:
    
      $ kubectl proxy --www=/my/files --www-prefix=/static/ --api-prefix=/api/
    
      # The above lets you 'curl localhost:8001/api/v1/pods'.
    
      # To proxy the entire kubernetes api at a different root, use:
    
      $ kubectl proxy --api-prefix=/custom/
    
      # The above lets you 'curl localhost:8001/custom/api/v1/pods'
    
      # Run a proxy to kubernetes apiserver on port 8011, serving static content from ./local/www/
      kubectl proxy --port=8011 --www=./local/www/
    
      # Run a proxy to kubernetes apiserver on an arbitrary local port.
      # The chosen port for the server will be output to stdout.
      kubectl proxy --port=0
    
      # Run a proxy to kubernetes apiserver, changing the api prefix to k8s-api
      # This makes e.g. the pods api available at localhost:8001/k8s-api/v1/pods/
      kubectl proxy --api-prefix=/k8s-api
    
    Options:
          --accept-hosts='^localhost$,^127\.0\.0\.1$,^\[::1\]$': Regular expression for hosts that the proxy should accept.
          --accept-paths='^.*': Regular expression for paths that the proxy should accept.
          --address='127.0.0.1': The IP address on which to serve on.
          --api-prefix='/': Prefix to serve the proxied API under.
          --disable-filter=false: If true, disable request filtering in the proxy. This is dangerous, and can leave you
    vulnerable to XSRF attacks, when used with an accessible port.
          --keepalive=0s: keepalive specifies the keep-alive period for an active network connection. Set to 0 to disable
    keepalive.
      -p, --port=8001: The port on which to run the proxy. Set to 0 to pick a random port.
          --reject-methods='^$': Regular expression for HTTP methods that the proxy should reject (example
    --reject-methods='POST,PUT,PATCH').
          --reject-paths='^/api/.*/pods/.*/exec,^/api/.*/pods/.*/attach': Regular expression for paths that the proxy should
    reject. Paths specified here will be rejected even accepted by --accept-paths.
      -u, --unix-socket='': Unix socket on which to run the proxy.
      -w, --www='': Also serve static files from the given directory under the specified prefix.
      -P, --www-prefix='/static/': Prefix to serve static files under, if static file directory is specified.
    
    Usage:
      kubectl proxy [--port=PORT] [--www=static-dir] [--www-prefix=prefix] [--api-prefix=prefix] [options]
    
    Use "kubectl options" for a list of global command-line options (applies to all commands).

     

    인증 생략 하여 api 사용 (내부 전송이라 인증이 필요 없음)

    background 로 실행 되고 api prefix 세팅

    주로 개발자가 로컬에서 테스트하기 위해 endpoint 제공(인증 방식이 아니라 간단하게 사용 가능하다)

    ps0107@k8smaster1:~$ kubectl proxy --api-prefix=/ &
    [1] 16218
    ps0107@k8smaster1:~$ Starting to serve on 127.0.0.1:8001

     

    http://127.0.0.1:8001/ 로 테스트 가능

    ps0107@k8smaster1:~$ curl http://127.0.0.1:8001/api/
    {
      "kind": "APIVersions",
      "versions": [
        "v1"
      ],
      "serverAddressByClientCIDRs": [
        {
          "clientCIDR": "0.0.0.0/0",
          "serverAddress": "10.146.0.2:6443"
        }
      ]
    }
    
    ps0107@k8smaster1:~$  curl http://127.0.0.1:8001/api/v1/namespaces
    {
      "kind": "NamespaceList",
      "apiVersion": "v1",
      "metadata": {
        "selfLink": "/api/v1/namespaces",
        "resourceVersion": "606177"
      },
      "items": [
        {
          "metadata": {
            "name": "default",
            "selfLink": "/api/v1/namespaces/default",
            "uid": "d001f113-42a9-49b6-ad1c-5dfdc9ce66fc",
            "resourceVersion": "149",
            "creationTimestamp": "2020-01-28T08:29:32Z"
          },
          "spec": {
            "finalizers": [
              "kubernetes"
            ]
          },
          "status": {
            "phase": "Active"
          }
        },
       .......

     

     

     


    Job 사용

    파라메터 설정 없이 기본 값으로 job 사용

    # restartPolicy 옵션
    - Always : deployment 객체로 생성
    - Never : 단순 Pod로 배포
    - Onfailure : Job기반
    ps0107@k8smaster1:~$ vi job.yaml
    apiVersion: batch/v1
    kind: Job
    metadata:
      name: sleepy
    spec:
      template:
        spec:
          containers:
          - name: resting
            image: busybox
            command: ["/bin/sleep"]
            args: ["3"]
          restartPolicy: Never #-> 원래는 OnFailure : 한번의 success를 보장. 중간에 장애 발생시 재시작

     

    job 생성      

    ps0107@k8smaster1:~$ kubectl create -f job.yaml
    job.batch/sleepy created

     

    생성된 job 확인

    ps0107@k8smaster1:~$ kubectl get job
    NAME     COMPLETIONS   DURATION   AGE
    sleepy   0/1           6s         6s

     

    job 상세 확인

    - Parallelism, Completions은 디폴트 값

    - Pods Statuses 확인 해보면 1번 Success 확인

    ps0107@k8smaster1:~$ kubectl describe jobs.batch sleepy
    Name:           sleepy
    Namespace:      default
    Selector:       controller-uid=138bbff0-02ae-45a5-bc7f-335125602d16
    Labels:         controller-uid=138bbff0-02ae-45a5-bc7f-335125602d16
                    job-name=sleepy
    Annotations:    <none>
    Parallelism:    1  # -> 기본값
    Completions:    1  # -> 기본값
    Start Time:     Sun, 02 Feb 2020 14:09:21 +0000
    Completed At:   Sun, 02 Feb 2020 14:09:29 +0000
    Duration:       8s
    Pods Statuses:  0 Running / 1 Succeeded / 0 Failed. # -> 성공 1회
    .....

     

    생성된 job 확인

    ps0107@k8smaster1:~$ kubectl get job
    NAME     COMPLETIONS   DURATION   AGE
    sleepy   1/1           8s         51s

     

    job 오브젝트 yaml 확인

    - spec 부분에 backoffLimit, completions, parallelism 파라메터 확인 가능.

    ps0107@k8smaster1:~$ kubectl get jobs.batch sleepy -o yaml
    ......
      uid: 138bbff0-02ae-45a5-bc7f-335125602d16
    spec:
      backoffLimit: 6
      completions: 1
      parallelism: 1
      selector:
        matchLabels:
          controller-uid: 138bbff0-02ae-45a5-bc7f-335125602d16
    ......

     

    생성한 오브젝트 삭제

    ps0107@k8smaster1:~$ kubectl delete jobs.batch sleepy
    job.batch "sleepy" deleted

     

    completions 파라메터 설정 해보기

    ps0107@k8smaster1:~$ vi job.yaml
    apiVersion: batch/v1
    kind: Job
    metadata:
      name: sleepy
    spec:
      completions: 5 # -> 추가
      template:
        spec:
          containers:
          - name: resting
            image: busybox
            command: ["/bin/sleep"]
            args: ["3"]
          restartPolicy: Never

     

    job 오브젝트 생성

    ps0107@k8smaster1:~$ kubectl create -f job.yaml
    job.batch/sleepy created

     

    job 배치 확인

    ps0107@k8smaster1:~$ kubectl get jobs.batch
    NAME     COMPLETIONS   DURATION   AGE
    sleepy   1/5           7s         7s

     

    pod 확인

    ps0107@k8smaster1:~$ kubectl get pods
    NAME           READY   STATUS      RESTARTS   AGE
    sleepy-94mw8   1/1     Running     0          4s
    sleepy-cl8px   0/1     Completed   0          18s
    sleepy-pffgc   0/1     Completed   0          11s
    
    ps0107@k8smaster1:~$ kubectl get pods
    NAME           READY   STATUS              RESTARTS   AGE
    sleepy-94mw8   0/1     Completed           0          15s
    sleepy-cl8px   0/1     Completed           0          29s
    sleepy-pffgc   0/1     Completed           0          22s
    sleepy-r8qpw   0/1     ContainerCreating   0          1s
    sleepy-wf2xt   0/1     Completed           0          8s

     

    생성한 job 오브젝트 삭제

    ps0107@k8smaster1:~$ kubectl delete jobs.batch sleepy
    job.batch "sleepy" deleted

     

    parallelism 파라메터(병렬처리) 설정 해보기

    parallelism 파라메터 추가

    ps0107@k8smaster1:~$ vi job.yaml
    apiVersion: batch/v1
    kind: Job
    metadata:
      name: sleepy
    spec: # -> pod 2개로 5회 완성이란 의미
      completions: 5
      parallelism: 2 # -> 병렬 처리
      template:
        spec:
          containers:
          - name: resting
            image: busybox
            command: ["/bin/sleep"]
            args: ["3"]
          restartPolicy: Never

     

    job 오브젝트 생성

    ps0107@k8smaster1:~$ kubectl create -f job.yaml
    job.batch/sleepy created

     

    pod 상태 확인

    ps0107@k8smaster1:~$ kubectl get pods
    NAME           READY   STATUS              RESTARTS   AGE
    sleepy-2v8jd   0/1     ContainerCreating   0          6s
    sleepy-xbj79   1/1     Running             0          6s
    
    ps0107@k8smaster1:~$ kubectl get pods
    NAME           READY   STATUS              RESTARTS   AGE
    sleepy-2v8jd   0/1     Completed           0          13s
    sleepy-t4kgz   0/1     ContainerCreating   0          2s
    sleepy-tl4rv   1/1     Running             0          5s
    sleepy-xbj79   0/1     Completed           0          13s
    
    ps0107@k8smaster1:~$ kubectl get pods
    NAME           READY   STATUS              RESTARTS   AGE
    sleepy-2v8jd   0/1     Completed           0          17s
    sleepy-g87m4   0/1     ContainerCreating   0          2s
    sleepy-t4kgz   1/1     Running             0          6s
    sleepy-tl4rv   0/1     Completed           0          9s
    sleepy-xbj79   0/1     Completed           0          17s

     

    job 오브젝트 삭제

    ps0107@k8smaster1:~$ kubectl delete jobs.batch sleepy
    job.batch "sleepy" deleted

     

    activeDeadlineSeconds 설정 해보기

    duration 지정, 15초안에 complete 안되면 uncomplete 됨. (참고로 이시간은 pod 생성 시간까지 포함됨)

    ps0107@k8smaster1:~$ vi job.yaml
    apiVersion: batch/v1
    kind: Job
    metadata:
      name: sleepy
    spec:
      completions: 5
      parallelism: 2
      activeDeadlineSeconds: 15 # -> duration 지정. 15초 안에 complete안되면 uncomplete됨. pod생성 시간 포함.
      template:
        spec:
          containers:
          - name: resting
            image: busybox
            command: ["/bin/sleep"]
            args: ["5"] 
          restartPolicy: Never

     

    job 오브젝트 생성

    ps0107@k8smaster1:~$ kubectl create -f job.yaml
    job.batch/sleepy created

     

    pod 상태 확인

    ps0107@k8smaster1:~$ kubectl get pods
    NAME           READY   STATUS              RESTARTS   AGE
    sleepy-rfd4q   0/1     ContainerCreating   0          5s
    sleepy-rtrk7   1/1     Running             0          5s
    
    ps0107@k8smaster1:~$ kubectl get pods
    NAME           READY   STATUS    RESTARTS   AGE
    sleepy-rfd4q   1/1     Running   0          8s
    sleepy-rtrk7   1/1     Running   0          8s
    
    ps0107@k8smaster1:~$ kubectl get pods
    NAME           READY   STATUS              RESTARTS   AGE
    sleepy-cqv8t   0/1     ContainerCreating   0          0s
    sleepy-rfd4q   1/1     Running             0          10s
    sleepy-rtrk7   0/1     Completed           0          10s

     

    job 확인

    ps0107@k8smaster1:~$ kubectl get jobs
    NAME     COMPLETIONS   DURATION   AGE
    sleepy   2/5           20s        20s
    
    ps0107@k8smaster1:~$ kubectl get jobs
    NAME     COMPLETIONS   DURATION   AGE
    sleepy   2/5           24s        24s
    
    ps0107@k8smaster1:~$ kubectl get jobs
    NAME     COMPLETIONS   DURATION   AGE
    sleepy   2/5           82s        82s
    
    ps0107@k8smaster1:~$ kubectl get job sleepy -o yaml
    ......
    status:
      conditions:
      - lastProbeTime: "2020-02-02T14:15:25Z"
        lastTransitionTime: "2020-02-02T14:15:25Z"
        message: Job was active longer than specified deadline
        reason: DeadlineExceeded
        status: "True"
        type: Failed
      failed: 2
      startTime: "2020-02-02T14:15:10Z"
      succeeded: 2

     

    job 오브젝트 삭제

    ps0107@k8smaster1:~$ kubectl delete jobs.batch sleepy
    job.batch "sleepy" deleted

     

     

     


    CronJob 사용

    cronjob 기본

    ps0107@k8smaster1:~$ vi cronjob.yaml
    apiVersion: batch/v1beta1
    kind: CronJob
    metadata:
      name: sleepy
    spec:
      schedule: "*/2 * * * *"
      jobTemplate:
        spec:
          template:
            spec:
              containers:
              - name: resting
                image: busybox
                command: ["/bin/sleep"]
                args: ["5"]
              restartPolicy: Never

     

    cronjob 객체 생성          

    ps0107@k8smaster1:~$ kubectl create -f cronjob.yaml
    cronjob.batch/sleepy created

     

    cronjob 상태 확인

    ps0107@k8smaster1:~$ kubectl get cronjobs.batch
    NAME     SCHEDULE      SUSPEND   ACTIVE   LAST SCHEDULE   AGE
    sleepy   */2 * * * *   False     0        <none>          11s
    
    ps0107@k8smaster1:~$ kubectl get jobs.batch
    No resources found.
    
    ps0107@k8smaster1:~$ kubectl get cronjobs.batch
    NAME     SCHEDULE      SUSPEND   ACTIVE   LAST SCHEDULE   AGE
    sleepy   */2 * * * *   False     0        31s             2m25s
    
    ps0107@k8smaster1:~$ kubectl get jobs.batch
    NAME                COMPLETIONS   DURATION   AGE
    sleepy-1580655480   1/1           10s        28s

     

    2분 후 새로운 job 확인

    ps0107@k8smaster1:~$ kubectl get jobs.batch
    NAME                COMPLETIONS   DURATION   AGE
    sleepy-1580655480   1/1           10s        2m6s
    sleepy-1580655600   0/1           5s         5s
    
    ps0107@k8smaster1:~$ kubectl delete cronjobs.batch sleepy
    cronjob.batch "sleepy" deleted

     

    cronjob activeDeadlineSeconds 파라메터 추가

    ps0107@k8smaster1:~$ vi cronjob.yaml
    apiVersion: batch/v1beta1
    kind: CronJob
    metadata:
      name: sleepy
    spec:
      schedule: "*/2 * * * *"
      jobTemplate:
        spec:
          template:
            spec:
              activeDeadlineSeconds: 10 # -> 10초 지나면 강제 종료
              containers:
              - name: resting
                image: busybox
                command: ["/bin/sleep"]
                args: ["5"]
              restartPolicy: Never
    
    ps0107@k8smaster1:~$ kubectl create -f cronjob.yaml
    cronjob.batch/sleepy created

     

    생성후 처음엔 job이 없음.

    ps0107@k8smaster1:~$ kubectl get jobs
    No resources found.
    
    ps0107@k8smaster1:~$ kubectl get cronjobs.batch
    NAME     SCHEDULE      SUSPEND   ACTIVE   LAST SCHEDULE   AGE
    sleepy   */2 * * * *   False     1        8s              30s
    
    ps0107@k8smaster1:~$ kubectl get jobs
    NAME                COMPLETIONS   DURATION   AGE
    sleepy-1580655720   1/1           9s         9s
    
    ps0107@k8smaster1:~$ kubectl get cronjobs.batch
    NAME     SCHEDULE      SUSPEND   ACTIVE   LAST SCHEDULE   AGE
    sleepy   */2 * * * *   False     0        36s             58s
    
    ps0107@k8smaster1:~$ kubectl get jobs
    NAME                COMPLETIONS   DURATION   AGE
    sleepy-1580655720   1/1           9s         38s
    
    ps0107@k8smaster1:~$ kubectl get cronjobs.batch
    NAME     SCHEDULE      SUSPEND   ACTIVE   LAST SCHEDULE   AGE
    sleepy   */2 * * * *   False     0        47s             69s
    
    ps0107@k8smaster1:~$ kubectl get jobs
    NAME                COMPLETIONS   DURATION   AGE
    sleepy-1580655720   1/1           9s         2m6s
    sleepy-1580655840   0/1           6s         6s
    
    ps0107@k8smaster1:~$ kubectl get cronjobs.batch
    NAME     SCHEDULE      SUSPEND   ACTIVE   LAST SCHEDULE   AGE
    sleepy   */2 * * * *   False     1        14s             2m36s
    
    ps0107@k8smaster1:~$ kubectl get jobs
    NAME                COMPLETIONS   DURATION   AGE
    sleepy-1580655720   1/1           9s         2m15s
    sleepy-1580655840   0/1           15s        15s
    
    ps0107@k8smaster1:~$ kubectl get cronjobs.batch
    NAME     SCHEDULE      SUSPEND   ACTIVE   LAST SCHEDULE   AGE
    sleepy   */2 * * * *   False     1        25s             2m47s
    
    ps0107@k8smaster1:~$ kubectl get cronjobs.batch
    NAME     SCHEDULE      SUSPEND   ACTIVE   LAST SCHEDULE   AGE
    sleepy   */2 * * * *   False     1        6s              4m28s

     

    오브젝트 삭제

    ps0107@k8smaster1:~$ kubectl delete cronjobs.batch sleepy
    cronjob.batch "sleepy" deleted

     


    참조) CKA 대비 간단 실습

    01. kubeadm 을 이용한 설치 및 세팅
    02. kubernetes 클러스터 노드 확장 및 셋팅
    03. 간단한 application 배포, yaml템플릿, 서비스 expose 해보기
    04. deployment 의 CPU, Memory 제약
    05. namespace 를 위한 resource limit 설정
    06. 좀더 복잡한 deployment 배포해보기
    07. 기본 Node 의 maintenance (유지보수)
    08. API AND ACCESS
    09. API 객체
    10. Managing State with Deployments
    11. Service Resource
    12. Volumes and Data : ConfigMap 간단 테스트
    13. PV 와 PVC 생성
    14. ResourceQuota 사용 (PVC Count 와 Usage를 제한)
    15. ingress 간단 실습
    16. Scheduling - label 사용한 pod 할당
    17. Scheduling - Taint를 이용한 pod 배포 관리
    18. 로깅과 트러블슈팅 : 로그위치와 로그 출력 보기
    19. 로깅과 트러블슈팅 : Metrics와 DashBoard
    20. CRD (Custom Resource Definition)
    21. helm
    22. Security - TLS
    23. Security - Authentication, Authorization, Admission
    24. HA(High Availability) 구성 - master node


    • 네이버 블로그 공유
    • 네이버 밴드 공유
    • 페이스북 공유
    • 카카오스토리 공유