반응형

 

초기 구성

# 필요 프로그램 설치
master@master:~$ sudo apt-get update
master@master:~$ sudo apt-get install -y docker.io
master@master:~$ sudo apt-get install -y nfs-common
master@master:~$ sudo apt-get install -y python3-dev
master@master:~$ sudo apt-get install -y python3-pip

# Master Node 필요 설정 및 버전 구성(중요)
master@master:~$ curl -sfL https://get.k3s.io | INSTALL_K3S_EXEC="\
    --disable traefik \
    --disable metrics-server \
    --node-name master --docker" \
    INSTALL_K3S_VERSION="v1.17.4+k3s1" sh -s -

# sudo 명령 없이 사용자 권한 설정 구성
master@master:~$ mkdir ~/.kube
master@master:~$ sudo cp /etc/rancher/k3s/k3s.yaml ~/.kube/config
master@master:~$ sudo chown -R $(id -u):$(id -g) ~/.kube
master@master:~$ echo "export KUBECONFIG=~/.kube/config" >> ~/.bashrc
master@master:~$ source ~/.bashrc
master@master:~$ kubectl get node
NAME     STATUS   ROLES    AGE     VERSION
master   Ready    master   2m42s   v1.17.4+k3s1
master@master:~$

 

반응형
반응형

Kubernetes 리소스 조회

# 리소스 조회
kubectl get namespace
kubectl get node
kubectl get pod

master@master:~$ kubectl get namespace
kubectl get node
kubectl get podNAME              STATUS   AGE
kube-system       Active   73m
default           Active   73m
kube-public       Active   73m
kube-node-lease   Active   73m
master@master:~$ kubectl get node
NAME     STATUS   ROLES    AGE   VERSION
master   Ready    master   73m   v1.17.4+k3s1
master@master:~$ kubectl get pod
NAME         READY   STATUS    RESTARTS   AGE
jinsunginx   1/1     Running   0          16m
master@master:~$

 

 

Kubernetes 모든 리소스 조회

# 클러스터에 모든 리소스 조회
master@master:~$ kubectl api-resources
NAME                              SHORTNAMES   APIGROUP                       NAMESPACED   KIND
bindings                                                                      true         Binding
componentstatuses                 cs                                          false        ComponentStatus
configmaps                        cm                                          true         ConfigMap
endpoints                         ep                                          true         Endpoints
events                            ev                                          true         Event
limitranges                       limits                                      true         LimitRange
namespaces                        ns                                          false        Namespace
nodes                             no                                          false        Node
persistentvolumeclaims            pvc                                         true         PersistentVolumeClaim
persistentvolumes                 pv                                          false        PersistentVolume
pods                              po                                          true         Pod
podtemplates                                                                  true         PodTemplate
replicationcontrollers            rc                                          true         ReplicationController
resourcequotas                    quota                                       true         ResourceQuota
secrets                                                                       true         Secret
serviceaccounts                   sa                                          true         ServiceAccount
services                          svc                                         true         Service
mutatingwebhookconfigurations                  admissionregistration.k8s.io   false        MutatingWebhookConfiguration
validatingwebhookconfigurations                admissionregistration.k8s.io   false        ValidatingWebhookConfiguration
customresourcedefinitions         crd,crds     apiextensions.k8s.io           false        CustomResourceDefinition
apiservices                                    apiregistration.k8s.io         false        APIService
controllerrevisions                            apps                           true         ControllerRevision
daemonsets                        ds           apps                           true         DaemonSet
deployments                       deploy       apps                           true         Deployment
replicasets                       rs           apps                           true         ReplicaSet
statefulsets                      sts          apps                           true         StatefulSet
tokenreviews                                   authentication.k8s.io          false        TokenReview
localsubjectaccessreviews                      authorization.k8s.io           true         LocalSubjectAccessReview
selfsubjectaccessreviews                       authorization.k8s.io           false        SelfSubjectAccessReview
selfsubjectrulesreviews                        authorization.k8s.io           false        SelfSubjectRulesReview
subjectaccessreviews                           authorization.k8s.io           false        SubjectAccessReview
horizontalpodautoscalers          hpa          autoscaling                    true         HorizontalPodAutoscaler
cronjobs                          cj           batch                          true         CronJob
jobs                                           batch                          true         Job
certificatesigningrequests        csr          certificates.k8s.io            false        CertificateSigningRequest
leases                                         coordination.k8s.io            true         Lease
endpointslices                                 discovery.k8s.io               true         EndpointSlice
events                            ev           events.k8s.io                  true         Event
ingresses                         ing          extensions                     true         Ingress
helmcharts                                     helm.cattle.io                 true         HelmChart
addons                                         k3s.cattle.io                  true         Addon
ingresses                         ing          networking.k8s.io              true         Ingress
networkpolicies                   netpol       networking.k8s.io              true         NetworkPolicy
runtimeclasses                                 node.k8s.io                    false        RuntimeClass
poddisruptionbudgets              pdb          policy                         true         PodDisruptionBudget
podsecuritypolicies               psp          policy                         false        PodSecurityPolicy
clusterrolebindings                            rbac.authorization.k8s.io      false        ClusterRoleBinding
clusterroles                                   rbac.authorization.k8s.io      false        ClusterRole
rolebindings                                   rbac.authorization.k8s.io      true         RoleBinding
roles                                          rbac.authorization.k8s.io      true         Role
priorityclasses                   pc           scheduling.k8s.io              false        PriorityClass
csidrivers                                     storage.k8s.io                 false        CSIDriver
csinodes                                       storage.k8s.io                 false        CSINode
storageclasses                    sc           storage.k8s.io                 false        StorageClass
volumeattachments                              storage.k8s.io                 false        VolumeAttachment
master@master:~$

 

 

 

자동완성 명령어

# 자동완성 기능
master@master:~$ echo "source <(kubectl completion bash)" >> ~/.bashrc
master@master:~$ source ~/.bashrc

 

 

사용자 인증 파일 확인

# kubectl 명령을 이용하여 확인
master@master:~$ kubectl config view
apiVersion: v1
clusters:
- cluster:
    certificate-authority-data: DATA+OMITTED
    server: https://127.0.0.1:6443
  name: default
contexts:
- context:
    cluster: default
    user: default
  name: default
current-context: default
kind: Config
preferences: {}
users:
- name: default
  user:
    password: 4275a8b14f67fb2159b6a7f88facc091
    username: admin
master@master:~$ 



# master node가 가지고 있는 config파일로 확인
master@master:~$ cat ~/.kube/config
apiVersion: v1
clusters:
- cluster:
    certificate-authority-data: LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUJWekNCL3FBREFnRUNBZ0VBTUFvR0NDcUdTTTQ5QkFNQ01DTXhJVEFmQmdOVkJBTU1HR3N6Y3kxelpYSjIKWlhJdFkyRkFNVFkxT1RnME5qa3hNakFlRncweU1qQTRNRGN3TkRNMU1USmFGdzB6TWpBNE1EUXdORE0xTVRKYQpNQ014SVRBZkJnTlZCQU1NR0dzemN5MXpaWEoyWlhJdFkyRkFNVFkxT1RnME5qa3hNakJaTUJNR0J5cUdTTTQ5CkFnRUdDQ3FHU000OUF3RUhBMElBQkR6S2t1bU1TbGVwd0VaSG9NeldidS9lSzRhT2RUQ1hWcHlEWVBmWXdCcjUKY0t0a2ZMVHZvVHZ6SG9pOXdrOU9TNC9CRHc3bHJxbHZoeHJZZ0dLYm02NmpJekFoTUE0R0ExVWREd0VCL3dRRQpBd0lDcERBUEJnTlZIUk1CQWY4RUJUQURBUUgvTUFvR0NDcUdTTTQ5QkFNQ0EwZ0FNRVVDSUdnVFFwZ3NROUJnCkJ5RVpJQlgrbzlsZVBsL0QwRi9VUGQ0azB0Zk4xVzQrQWlFQW9WdVBoUWtPNXd4bjJkU1Jtck5lYW9BbWlLeGsKL0hGRWlBQlNoRUhSblZZPQotLS0tLUVORCBDRVJUSUZJQ0FURS0tLS0tCg==
    server: https://127.0.0.1:6443
  name: default
contexts:
- context:
    cluster: default
    user: default
  name: default
current-context: default
kind: Config
preferences: {}
users:
- name: default
  user:
    password: 4275a8b14f67fb2159b6a7f88facc091
    username: admin
master@master:~$

 

 

 

클러스터 상태 확인

# Cluster 상태 확인
master@master:~$ kubectl cluster-info
Kubernetes master is running at https://127.0.0.1:6443
CoreDNS is running at https://127.0.0.1:6443/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy

To further debug and diagnose cluster problems, use 'kubectl cluster-info dump'.
master@master:~$

 

 

 

 

 

참고자료

https://kubernetes.io/ko/docs/reference/kubectl/cheatsheet/

 

 

 

 

 

반응형

'Kubernetes' 카테고리의 다른 글

[K8S] 쿠버네티스 - YAML 파일로 Pod 생성  (0) 2022.08.07
[K8S] 쿠버네티스 - k3s 구성  (0) 2022.08.07
[K8S] 쿠버네티스 - Pod 구성  (0) 2022.08.07
[K8S] 쿠버네티스 설치  (0) 2022.08.07
[K8S] Kubernetes 란 무엇인가?  (0) 2022.08.07
반응형

파드

파드(Pod) 는 쿠버네티스에서 생성하고 관리할 수 있는 배포 가능한 가장 작은 컴퓨팅 단위이다.

파드 (고래 떼(pod of whales)나 콩꼬투리(pea pod)와 마찬가지로)는 하나 이상의 컨테이너의 그룹이다. 이 그룹은 스토리지 및 네트워크를 공유하고, 해당 컨테이너를 구동하는 방식에 대한 명세를 갖는다. 파드의 콘텐츠는 항상 함께 배치되고, 함께 스케줄되며, 공유 콘텍스트에서 실행된다. 파드는 애플리케이션 별 "논리 호스트"를 모델링한다. 여기에는 상대적으로 밀접하게 결합된 하나 이상의 애플리케이션 컨테이너가 포함된다. 클라우드가 아닌 콘텍스트에서, 동일한 물리 또는 가상 머신에서 실행되는 애플리케이션은 동일한 논리 호스트에서 실행되는 클라우드 애플리케이션과 비슷하다.

애플리케이션 컨테이너와 마찬가지로, 파드에는 파드 시작 중에 실행되는 초기화 컨테이너가 포함될 수 있다. 클러스터가 제공하는 경우, 디버깅을 위해 임시 컨테이너를 삽입할 수도 있다.

 

파드란 무엇인가?

참고 : 도커가 가장 일반적으로 잘 알려진 컨테이너 런타임이지만, 쿠버네티스는 도커 외에도 다양한 컨테이너 런타임을 지원하며, 파드를 설명할 때 도커 관련 용어를 사용하면 더 쉽게 설명할 수 있다.

파드의 공유 콘텍스트는 리눅스 네임스페이스, 컨트롤 그룹(cgroup) 및 도커 컨테이너를 격리하는 것과 같이 잠재적으로 다른 격리 요소들이다. 파드의 콘텍스트 내에서 개별 애플리케이션은 추가적으로 하위 격리가 적용된다.

도커 개념 측면에서, 파드는 공유 네임스페이스와 공유 파일시스템 볼륨이 있는 도커 컨테이너 그룹과 비슷하다

 

 

 

 

Pod 생성 및 실행

# Pod 생성 및 실행
master@master:~$ kubectl run jinsunginx --image nginx --restart Never           
pod/jinsunginx created
master@master:~$

 

 

Pod 실행 상태 확인

# Pod 실행 상태 확인
master@master:~$ kubectl get pod jinsunginx
NAME         READY   STATUS    RESTARTS   AGE
jinsunginx   1/1     Running   0          52s
master@master:~$

 

 

Pod YAML 정의서 상세내용 확인

# Pod YAML 정의서 상세확인
master@master:~$ kubectl get pod jinsunginx -o yaml       
apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: "2022-08-07T04:51:41Z"
  labels:
    run: jinsunginx
  name: jinsunginx
  namespace: default
  resourceVersion: "1035"
  selfLink: /api/v1/namespaces/default/pods/jinsunginx
  uid: db8ef4a7-de65-421d-9b08-c835b8050eff
spec:
  containers:
  - image: nginx
    imagePullPolicy: Always
    name: jinsunginx
    resources: {}
    terminationMessagePath: /dev/termination-log
    terminationMessagePolicy: File
    volumeMounts:
    - mountPath: /var/run/secrets/kubernetes.io/serviceaccount
      name: default-token-g8wm6
      readOnly: true
  dnsPolicy: ClusterFirst
  enableServiceLinks: true
  nodeName: master
  priority: 0
  restartPolicy: Never
  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: default-token-g8wm6
    secret:
      defaultMode: 420
      secretName: default-token-g8wm6
status:
  conditions:
  - lastProbeTime: null
    lastTransitionTime: "2022-08-07T04:51:41Z"
    status: "True"
    type: Initialized
  - lastProbeTime: null
    lastTransitionTime: "2022-08-07T04:51:52Z"
    status: "True"
    type: Ready
  - lastProbeTime: null
    lastTransitionTime: "2022-08-07T04:51:52Z"
    status: "True"
    type: ContainersReady
  - lastProbeTime: null
    lastTransitionTime: "2022-08-07T04:51:41Z"
    status: "True"
    type: PodScheduled
  containerStatuses:
  - containerID: docker://f132455cc278b02f7ac431e962237eb7fa3e69537e63a4299dabf2f11f6b4e07
    image: nginx:latest
    imageID: docker-pullable://nginx@sha256:ecc068890de55a75f1a32cc8063e79f90f0b043d70c5fcf28f1713395a4b3d49
    lastState: {}
    name: jinsunginx
    ready: true
    restartCount: 0
    started: true
    state:
      running:
        startedAt: "2022-08-07T04:51:52Z"
  hostIP: 192.168.0.201
  phase: Running
  podIP: 10.42.0.4
  podIPs:
  - ip: 10.42.0.4
  qosClass: BestEffort
  startTime: "2022-08-07T04:51:41Z"
master@master:~$

 

 

Pod 정보 확인

# Pod 정보 확인
master@master:~$ kubectl describe pod jinsunginx
Name:         jinsunginx
Namespace:    default
Priority:     0
Node:         master/192.168.0.201
Start Time:   Sun, 07 Aug 2022 04:51:41 +0000
Labels:       run=jinsunginx
Annotations:  <none>
Status:       Running
IP:           10.42.0.4
IPs:
  IP:  10.42.0.4
Containers:
  jinsunginx:
    Container ID:   docker://f132455cc278b02f7ac431e962237eb7fa3e69537e63a4299dabf2f11f6b4e07
    Image:          nginx
    Image ID:       docker-pullable://nginx@sha256:ecc068890de55a75f1a32cc8063e79f90f0b043d70c5fcf28f1713395a4b3d49
    Port:           <none>
    Host Port:      <none>
    State:          Running
      Started:      Sun, 07 Aug 2022 04:51:52 +0000
    Ready:          True
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-g8wm6 (ro)
Conditions:
  Type              Status
  Initialized       True 
  Ready             True 
  ContainersReady   True 
  PodScheduled      True 
Volumes:
  default-token-g8wm6:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-g8wm6
    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  <unknown>  default-scheduler  Successfully assigned default/jinsunginx to master
  Normal  Pulling    9m7s       kubelet, master    Pulling image "nginx"
  Normal  Pulled     8m57s      kubelet, master    Successfully pulled image "nginx"
  Normal  Created    8m57s      kubelet, master    Created container jinsunginx
  Normal  Started    8m57s      kubelet, master    Started container jinsunginx
master@master:~$

 

 

Pod 명령 내리기

# Pod 명령 내리기
master@master:~$ kubectl exec jinsunginx -- apt update

WARNING: apt does not have a stable CLI interface. Use with caution in scripts.

Get:1 http://deb.debian.org/debian bullseye InRelease [116 kB]
Get:2 http://deb.debian.org/debian-security bullseye-security InRelease [48.4 kB]
Get:3 http://deb.debian.org/debian bullseye-updates InRelease [44.1 kB]
Get:4 http://deb.debian.org/debian bullseye/main amd64 Packages [8182 kB]
Get:5 http://deb.debian.org/debian-security bullseye-security/main amd64 Packages [170 kB]
Get:6 http://deb.debian.org/debian bullseye-updates/main amd64 Packages [2592 B]
Fetched 8563 kB in 1s (5924 kB/s)
Reading package lists...
Building dependency tree...
Reading state information...
All packages are up to date.
master@master:~$ 
master@master:~$ 
master@master:~$ kubectl exec jinsunginx -- apt install -y curl

WARNING: apt does not have a stable CLI interface. Use with caution in scripts.

Reading package lists...
Building dependency tree...
Reading state information...
curl is already the newest version (7.74.0-1.3+deb11u2).
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
master@master:~$

 

 

Pod logs 확인 

# Pod 로그 확인
master@master:~$ kubectl logs jinsunginx
/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: 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
2022/08/07 04:51:52 [notice] 1#1: using the "epoll" event method
2022/08/07 04:51:52 [notice] 1#1: nginx/1.23.1
2022/08/07 04:51:52 [notice] 1#1: built by gcc 10.2.1 20210110 (Debian 10.2.1-6) 
2022/08/07 04:51:52 [notice] 1#1: OS: Linux 4.15.0-189-generic
2022/08/07 04:51:52 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 1048576:1048576
2022/08/07 04:51:52 [notice] 1#1: start worker processes
2022/08/07 04:51:52 [notice] 1#1: start worker process 31
2022/08/07 04:51:52 [notice] 1#1: start worker process 32
2022/08/07 04:51:52 [notice] 1#1: start worker process 33
2022/08/07 04:51:52 [notice] 1#1: start worker process 34
127.0.0.1 - - [07/Aug/2022:05:11:16 +0000] "GET / HTTP/1.1" 200 615 "-" "Wget/1.21" "-"
master@master:~$

 

 

Pod 파일 이동 복사

# 로컬에서 Pod로 파일 이동 및 복사
master@master:~$ kubectl cp ~/.bashrc jinsunginx:/.
master@master:~$ 
master@master:~$ kubectl exec jinsunginx -- cat /.bashrc
# ~/.bashrc: executed by bash(1) for non-login shells.
# see /usr/share/doc/bash/examples/startup-files (in the package bash-doc)
# for examples

# If not running interactively, don't do anything
case $- in
    *i*) ;;
      *) return;;
esac

# don't put duplicate lines or lines starting with space in the history.
# See bash(1) for more options
HISTCONTROL=ignoreboth
...

 

 

Pod 값 수정

# Pod를 수정
master@master:~$ kubectl edit pod jinsunginx
# Please edit the object below. Lines beginning with a '#' will be ignored,
# and an empty file will abort the edit. If an error occurs while saving this file will be
# reopened with the relevant failures.
#
apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: "2022-08-07T04:51:41Z"
  labels:
    run: jinsunginx
  name: jinsunginx
  namespace: default
  resourceVersion: "1035"
  selfLink: /api/v1/namespaces/default/pods/jinsunginx
  uid: db8ef4a7-de65-421d-9b08-c835b8050eff
spec:
  containers:
  - image: nginx
    imagePullPolicy: Always
    name: jinsunginx
    resources: {}
    terminationMessagePath: /dev/termination-log
    terminationMessagePolicy: File
    volumeMounts:
    - mountPath: /var/run/secrets/kubernetes.io/serviceaccount
      name: default-token-g8wm6
      readOnly: true
  dnsPolicy: ClusterFirst
  enableServiceLinks: true
  nodeName: master
  priority: 0
  restartPolicy: Never
  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: default-token-g8wm6
    secret:
      defaultMode: 420
      secretName: default-token-g8wm6

 

 

Pod 삭제

# 생성한 Pod 삭제하기
master@master:~$ kubectl delete pod jinsunginx
pod "jinsunginx" deleted

master@master:~$

 

 

생성된 Pod 변경(수정)

# 변경하고 싶은 Pod를 수정
master@master:~$  kubectl edit pods webapp-color

# 수정하고나면 에러로그 발생
error: pods "webapp-color" is invalid
A copy of your changes has been stored to "/tmp/kubectl-edit-3440084507.yaml"
error: Edit cancelled, no valid changes were saved.

# 해당 Pod의 yaml파일을 replace 해주면 됩니다.
master@master:~$  kubectl replace --force -f /tmp/kubectl-edit-3440084507.yaml
pod "webapp-color" deleted
pod/webapp-color replaced

 

 

 

 

 

 

 

 

 

 

 

참고자료

https://kubernetes.io/ko/docs/concepts/workloads/pods/

 

 

 

반응형

+ Recent posts