반응형

 

 

 

 

컨테이너 프로브(probe)

프로브 는 컨테이너에서 kubelet에 의해 주기적으로 수행되는 진단(diagnostic)이다. 진단을 수행하기 위해서, kubelet은 컨테이너 안에서 코드를 실행하거나, 또는 네트워크 요청을 전송한다.

 

 

Check 순서 

프로브를 사용하여 컨테이너를 체크하는 방법에는 4가지가 있다. 각 프로브는 다음의 4가지 메커니즘 중 단 하나만을 정의해야 한다.

  • exec - 컨테이너 내에서 지정된 명령어를 실행한다. 명령어가 상태 코드 0으로 종료되면 진단이 성공한 것으로 간주한다.
  • grpc - gRPC를 사용하여 원격 프로시저 호출을 수행한다. 체크 대상이 gRPC 헬스 체크를 구현해야 한다. 응답의 status 가 SERVING 이면 진단이 성공했다고 간주한다. gRPC 프로브는 알파 기능이며 GRPCContainerProbe 기능 게이트를 활성화해야 사용할 수 있다.
  • httpGet - 지정한 포트 및 경로에서 컨테이너의 IP주소에 대한 HTTP GET 요청을 수행한다. 응답의 상태 코드가 200 이상 400 미만이면 진단이 성공한 것으로 간주한다.
  • tcpSocket - 지정된 포트에서 컨테이너의 IP주소에 대해 TCP 검사를 수행한다. 포트가 활성화되어 있다면 진단이 성공한 것으로 간주한다. 원격 시스템(컨테이너)가 연결을 연 이후 즉시 닫는다면, 이 또한 진단이 성공한 것으로 간주한다.

 

프로브 결과

각 probe는 다음 세 가지 결과 중 하나를 가진다.

  • Success - 컨테이너가 진단을 통과함.
  • Failure - 컨테이너가 진단에 실패함.
  • Unknown - 진단 자체가 실패함(아무런 조치를 수행해서는 안 되며, kubelet이 추가 체크를 수행할 것이다)

 

 

프로브 종류

kubelet은 실행 중인 컨테이너들에 대해서 선택적으로 세 가지 종류의 프로브를 수행하고 그에 반응할 수 있다.

  • livenessProbe - 컨테이너가 동작 중인지 여부를 나타낸다. 만약 활성 프로브(liveness probe)에 실패한다면, kubelet은 컨테이너를 죽이고, 해당 컨테이너는 재시작 정책의 대상이 된다. 만약 컨테이너가 활성 프로브를 제공하지 않는 경우, 기본 상태는 Success 이다.
  • readinessProbe - 컨테이너가 요청을 처리할 준비가 되었는지 여부를 나타낸다. 만약 준비성 프로브(readiness probe)가 실패한다면, 엔드포인트 컨트롤러는 파드에 연관된 모든 서비스들의 엔드포인트에서 파드의 IP주소를 제거한다. 준비성 프로브의 초기 지연 이전의 기본 상태는 Failure 이다. 만약 컨테이너가 준비성 프로브를 지원하지 않는다면, 기본 상태는 Success 이다.
  • startupProbe - 컨테이너 내의 애플리케이션이 시작되었는지를 나타낸다. 스타트업 프로브(startup probe)가 주어진 경우, 성공할 때까지 다른 나머지 프로브는 활성화되지 않는다. 만약 스타트업 프로브가 실패하면, kubelet이 컨테이너를 죽이고, 컨테이너는 재시작 정책에 따라 처리된다. 컨테이너에 스타트업 프로브가 없는 경우, 기본 상태는 Success 이다.

 

 

 

 

 

Health Check 기능

livenessProve

# livenessProbe 커맨드를 추가하여 해당 Pod가 정상인지 health check jinsu@jinsu:~$ cat liveness.yaml apiVersion: v1 kind: Pod metadata: ​​name: liveness spec: ​​containers: ​​- name: mynginx ​​​​image: nginx ​​​​livenessProbe: ​​​​​​httpGet: ​​​​​​​​path: / ​​​​​​​​port: 80 # READY 부분이 1/1로 정상임을 확인 jinsu@jinsu:~$ kubectl get pod NAME READY STATUS RESTARTS AGE liveness 1/1 Running 0 2m19s jinsu@jinsu:~$

readnessProve

# readinessProve 커맨드를 추가하여 80포트를 Health check jinsu@jinsu:~$ cat readiness.yaml apiVersion: v1 kind: Pod metadata: ​​name: readiness spec: ​​containers: ​​- name: mynginx ​​​​image: nginx ​​​​readinessProbe: ​​​​​​httpGet: ​​​​​​​​path: / ​​​​​​​​port: 80 jinsu@jinsu:~$ # READY 상태를 체크하여 1/1 정상임을 확인 jinsu@jinsu:~$ kubectl get pod NAME READY STATUS RESTARTS AGE liveness 1/1 Running 0 3m50s readiness 1/1 Running 0 14s jinsu@jinsu:~$

exec를 이용하여 health check

# readinessProbe와 exec를 추가하여 pod안에 moby파일이 여부에 따라 상태 체크 jinsu@jinsu:~$ cat readiness-command.yaml apiVersion: v1 kind: Pod metadata: ​​name: readiness-command spec: ​​containers: ​​- name: mynginx ​​​​image: nginx ​​​​readinessProbe: ​​​​​​exec: ​​​​​​​​command: [ "ls", "/work-dir/moby" ] ​​​​volumeMounts: ​​​​- name: workdir ​​​​​​mountPath: "/work-dir" ​​initContainers: ​​- name: git ​​​​image: alpine/git ​​​​command: ["sh"] ​​​​args: ​​​​- "-c" ​​​​- "git clone https://github.com/moby/moby.git \ ​​​​​​​​​​/work-dir/moby" ​​​​volumeMounts: ​​​​- name: workdir ​​​​​​mountPath: "/work-dir" ​​volumes: ​​- name: workdir ​​​​emptyDir: {} jinsu@jinsu:~$ jinsu@jinsu:~$ kubectl get pod NAME READY STATUS RESTARTS AGE readiness-command 0/1 Running 0 47s jinsu@jinsu:~$ # moby 디렉토리를 삭제해봅니다. jinsu@jinsu:~$ kubectl exec readiness-command -- rm -rf /work-dir/moby jinsu@jinsu:~$ kubectl get pod NAME READY STATUS RESTARTS AGE readiness-command 1/1 Running 0 2m17s jinsu@jinsu:~$ # READY항복이 0으로 변경된것을 확인할 수 있습니다. jinsu@jinsu:~$ kubectl get pod NAME READY STATUS RESTARTS AGE readiness-command 0/1 Running 0 2m36s jinsu@jinsu:~$

 

 

 

 

참고자료

https://kubernetes.io/ko/docs/concepts/workloads/pods/pod-lifecycle/

반응형
반응형

 

 

 

init 컨테이너

초기화 컨테이너는 파드의 앱 컨테이너들이 실행되기 전에 실행되는 특수한 컨테이너이다. 초기화 컨테이너는 앱 이미지에는 없는 유틸리티 또는 설정 스크립트 등을 포함할 수 있다.

초기화 컨테이너는 containers 배열(앱 컨테이너를 기술하는)과 나란히 파드 스펙에 명시할 수 있다.

 

init 컨테이너 이해하기

파드는 앱들을 실행하는 다수의 컨테이너를 포함할 수 있고, 또한 앱 컨테이너 실행 전에 동작되는 하나 이상의 초기화 컨테이너도 포함할 수 있다.

다음의 경우를 제외하면, 초기화 컨테이너는 일반적인 컨테이너와 매우 유사하다.

  • 초기화 컨테이너는 항상 완료를 목표로 실행된다.
  • 각 초기화 컨테이너는 다음 초기화 컨테이너가 시작되기 전에 성공적으로 완료되어야 한다.

만약 파드의 초기화 컨테이너가 실패하면, kubelet은 초기화 컨테이너가 성공할 때까지 반복적으로 재시작한다. 그러나, 만약 파드의 restartPolicy 를 절대 하지 않음(Never)으로 설정하고, 해당 파드를 시작하는 동안 초기화 컨테이너가 실패하면, 쿠버네티스는 전체 파드를 실패한 것으로 처리한다.

컨테이너를 초기화 컨테이너로 지정하기 위해서는, 파드 스펙에 initContainers 필드를 container 항목(앱 container 필드 및 내용과 유사한)들의 배열로서 추가한다. 컨테이너에 대한 더 상세한 사항은 API 레퍼런스를 참고한다.

초기화 컨테이너의 상태는 컨테이너 상태의 배열(.status.containerStatuses 필드와 유사)로 .status.initContainerStatuses 필드에 반환된다.

일반적인 컨테이너와의 차이점

초기화 컨테이너는 앱 컨테이너의 리소스 상한(limit), 볼륨, 보안 세팅을 포함한 모든 필드와 기능을 지원한다. 그러나, 초기화 컨테이너를 위한 리소스 요청량과 상한은 리소스에 문서화된 것처럼 다르게 처리된다.

또한, 초기화 컨테이너는 lifecycle, livenessProbe, readinessProbe 또는 startupProbe 를 지원하지 않는다. 왜냐하면 초기화 컨테이너는 파드가 준비 상태가 되기 전에 완료를 목표로 실행되어야 하기 때문이다.

만약 다수의 초기화 컨테이너가 파드에 지정되어 있다면, kubelet은 해당 초기화 컨테이너들을 한 번에 하나씩 실행한다. 각 초기화 컨테이너는 다음 컨테이너를 실행하기 전에 꼭 성공해야 한다. 모든 초기화 컨테이너들이 실행 완료되었을 때, kubelet은 파드의 애플리케이션 컨테이너들을 초기화하고 평소와 같이 실행한다

 

 

init 컨테이너를 이용하여 pod 생성

# YAML 파일을 이용하여 init 컨테이너 생성 master@master:~$ cat init-container.yaml apiVersion: v1 kind: Pod metadata: ​​name: init-container spec: ​​containers: ​​- name: busybox ​​​​image: k8s.gcr.io/busybox ​​​​command: [ "ls" ] ​​​​args: [ "/work-dir/moby" ] ​​​​volumeMounts: ​​​​- name: workdir ​​​​​​mountPath: /work-dir ​​initContainers: ​​- name: git ​​​​image: alpine/git ​​​​command: ["sh"] ​​​​args: ​​​​- "-c" ​​​​- "git clone https://github.com/moby/moby.git \ ​​​​​​​​​​/work-dir/moby" ​​​​volumeMounts: ​​​​- name: workdir ​​​​​​mountPath: "/work-dir" ​​volumes: ​​- name: workdir ​​​​emptyDir: {} master@master:~$ master@master:~$ kubectl apply -f init-container.yaml pod/init-container created master@master:~$ master@master:~$ kubectl get pod NAME READY STATUS RESTARTS AGE init-container 0/1 Init:0/1 0 10s master@master:~$ master@master:~$ kubectl logs init-container Error from server (BadRequest): container "busybox" in pod "init-container" is waiting to start: PodInitializing master@master:~$ kubectl logs init-container -c git Cloning into '/work-dir/moby'... master@master:~$ kubectl logs init-container -c git -f Cloning into '/work-dir/moby'... Updating files: 100% (7258/7258), done. master@master:~$ master@master:~$ kubectl logs init-container AUTHORS CHANGELOG.md CONTRIBUTING.md Dockerfile Dockerfile.e2e Dockerfile.simple Dockerfile.windows Jenkinsfile LICENSE MAINTAINERS Makefile NOTICE README.md ROADMAP.md SECURITY.md TESTING.md VENDORING.md api builder cli client cmd codecov.yml container contrib daemon distribution docker-bake.hcl dockerversion docs errdefs hack image integration integration-cli internal layer libcontainerd libnetwork oci opts pkg plugin profiles project quota reference registry reports restartmanager rootless runconfig testutil vendor vendor.mod vendor.sum volume master@master:~$

 

 

 

 

참고자료

https://kubernetes.io/ko/docs/concepts/workloads/pods/init-containers/

 

 

반응형
반응형

 

 

 

 

 

 

파드안에 두개이상 컨테이너 생성 및 확인

YAML파일안에 sleep 5초를 준 이유는 Pod 안에 컨테이너가 동시에 시작되면 nginx 컨테이너에 오류가 발생할 수 있기에 mynginx 컨테이너 먼저 러닝상태가 되면 jinsunginx 컨테이너가 동작할 수 있게 옵션을 준 것입니다.

# 파드안에 두개의 컨테이너 생성하는 YAML파일 생성 master@master:~$ cat two-container.yaml apiVersion: v1 kind: Pod metadata: ​​name: mynginx spec: ​​containers: ​​- name: mynginx ​​​​image: nginx ​​- name: jinsunginx ​​​​image: curlimages/curl ​​​​command: ["sh"] ​​​​args: ​​​​- "-c" ​​​​- "sleep 5 && curl localhost" master@master:~$ master@master:~$ kubectl apply -f two-container.yaml pod/mynginx created master@master:~$ master@master:~$ kubectl get pod NAME READY STATUS RESTARTS AGE mynginx 1/2 Running 0 18s master@master:~$ # 그냥 pod의 logs를 조회하면 컨테이너를 선택하라는 문구가 나온다. master@master:~$ kubectl logs mynginx error: a container name must be specified for pod mynginx, choose one of: [mynginx jinsunginx] # 두개의 컨테이너가 있을떄는 -c 옵션을 사용한다. master@master:~$ kubectl logs mynginx -c mynginx /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/09 12:59:15 [notice] 1#1: using the "epoll" event method 2022/08/09 12:59:15 [notice] 1#1: nginx/1.23.1 2022/08/09 12:59:15 [notice] 1#1: built by gcc 10.2.1 20210110 (Debian 10.2.1-6) 2022/08/09 12:59:15 [notice] 1#1: OS: Linux 4.15.0-189-generic 2022/08/09 12:59:15 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 1048576:1048576 2022/08/09 12:59:15 [notice] 1#1: start worker processes 2022/08/09 12:59:15 [notice] 1#1: start worker process 32 2022/08/09 12:59:15 [notice] 1#1: start worker process 33 2022/08/09 12:59:15 [notice] 1#1: start worker process 34 2022/08/09 12:59:15 [notice] 1#1: start worker process 35 127.0.0.1 - - [09/Aug/2022:12:59:28 +0000] "GET / HTTP/1.1" 200 615 "-" "curl/7.84.0-DEV" "-" 127.0.0.1 - - [09/Aug/2022:12:59:36 +0000] "GET / HTTP/1.1" 200 615 "-" "curl/7.84.0-DEV" "-" 127.0.0.1 - - [09/Aug/2022:12:59:58 +0000] "GET / HTTP/1.1" 200 615 "-" "curl/7.84.0-DEV" "-" master@master:~$ master@master:~$ kubectl logs mynginx error: a container name must be specified for pod mynginx, choose one of: [mynginx jinsunginx] master@master:~$ kubectl logs mynginx -c jinsunginx % Total % Received % Xferd Average Speed Time Time Time Current ​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​Dload Upload Total Spent Left Speed 100 615 100 615 0 0 1002k 0 --:--:-- --:--:-- --:--:-- 600k <!DOCTYPE html> <html> <head> <title>Welcome to nginx!</title> <style> html { color-scheme: light dark; } 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> master@master:~$

 

 

 

참고자료

https://kubernetes.io/ko/docs/tasks/access-application-cluster/communicate-containers-same-pod-shared-volume/

 

반응형
반응형

 

파드 및 컨테이너 리소스 관리

파드를 생성 및 지정할 때, 컨테이너에 필요한 리소스의 자원을 선택하여 지정할 수 있다. 지정할 가장 일반적인 리소스는 CPU와 메모리(RAM) 그리고 다른 것들이 있다.

파드에서 컨테이너에 대한 리소스 요청(request) 을 지정하면, kube-scheduler는 이 정보를 사용하여 파드가 배치될 노드를 결정한다. 컨테이너에 대한 리소스 제한(limit) 을 지정하면, kubelet은 실행 중인 컨테이너가 설정한 제한보다 많은 리소스를 사용할 수 없도록 해당 제한을 적용한다. 또한 kubelet은 컨테이너가 사용할 수 있도록 해당 시스템 리소스의 최소 요청 자원을 예약한다.

요청 및 제한

파드가 실행 중인 노드에 사용 가능한 리소스가 충분하면, 컨테이너가 해당 리소스에 지정한 request 보다 더 많은 리소스를 사용할 수 있도록 허용된다. 그러나, 컨테이너는 리소스 limit 보다 더 많은 리소스를 사용할 수는 없다.

예를 들어, 컨테이너에 대해 256MiB의 memory 요청을 설정하고, 해당 컨테이너가 8GiB의 메모리를 가진 노드로 스케줄된 파드에 있고 다른 파드는 없는 경우, 컨테이너는 더 많은 RAM을 사용할 수 있다.

해당 컨테이너에 대해 4GiB의 memory 제한을 설정하면, kubelet(그리고 컨테이너 런타임)이 제한을 적용한다. 런타임은 컨테이너가 구성된 리소스 제한을 초과하여 사용하지 못하게 한다. 예를 들어, 컨테이너의 프로세스가 허용된 양보다 많은 메모리를 사용하려고 하면, 시스템 커널은 메모리 부족(out of memory, OOM) 오류와 함께 할당을 시도한 프로세스를 종료한다.

제한은 반응적(시스템이 위반을 감지한 후에 개입)으로 또는 강제적(시스템이 컨테이너가 제한을 초과하지 않도록 방지)으로 구현할 수 있다. 런타임마다 다른 방식으로 동일한 제약을 구현할 수 있다.

 

파드와 컨테이너의 리소스 요청 및 제한

각 컨테이너에 대해, 다음과 같은 리소스 제한(limit) 및 요청(request)을 지정할 수 있다.

  • spec.containers[].resources.limits.cpu
  • spec.containers[].resources.limits.memory
  • spec.containers[].resources.limits.hugepages-<size>
  • spec.containers[].resources.requests.cpu
  • spec.containers[].resources.requests.memory
  • spec.containers[].resources.requests.hugepages-<size>

 

쿠버네티스의 리소스 단위

CPU 리소스 단위

CPU 리소스에 대한 제한 및 요청은 cpu 단위로 측정된다. 쿠버네티스에서, 1 CPU 단위는 노드가 물리 호스트인지 아니면 물리 호스트 내에서 실행되는 가상 머신인지에 따라 1 물리 CPU 코어 또는 1 가상 코어 에 해당한다.

요청량을 소수점 형태로 명시할 수도 있다. 컨테이너의 spec.containers[].resources.requests.cpu를 0.5로 설정한다는 것은, 1.0 CPU를 요청했을 때와 비교하여 절반의 CPU 타임을 요청한다는 의미이다. CPU 자원의 단위와 관련하여, 0.1 이라는 수량 표현은 "백 밀리cpu"로 읽을 수 있는 100m 표현과 동일하다. 어떤 사람들은 "백 밀리코어"라고 말하는데, 같은 것을 의미하는 것으로 이해된다.

CPU 리소스는 항상 리소스의 절대량으로 표시되며, 상대량으로 표시되지 않는다. 예를 들어, 컨테이너가 싱글 코어, 듀얼 코어, 또는 48 코어 머신 중 어디에서 실행되는지와 상관없이 500m CPU는 거의 같은 양의 컴퓨팅 파워를 가리킨다.

참고: 쿠버네티스에서 CPU 리소스를 1m보다 더 정밀한 단위로 표기할 수 없다. 이 때문에, CPU 단위를 1.0 또는 1000m보다 작은 밀리CPU 형태로 표기하는 것이 유용하다. 예를 들어, 0.005 보다는 5m으로 표기하는 것이 좋다.

메모리 리소스 단위

memory 에 대한 제한 및 요청은 바이트 단위로 측정된다. E, P, T, G, M, k 와 같은 수량 접미사 중 하나를 사용하여 메모리를 일반 정수 또는 고정 소수점 숫자로 표현할 수 있다. Ei, Pi, Ti, Gi, Mi, Ki와 같은 2의 거듭제곱을 사용할 수도 있다. 예를 들어, 다음은 대략 동일한 값을 나타낸다.

128974848, 129e6, 129M, 128974848000m, 123Mi

접미사의 대소문자에 유의한다. 400m의 메모리를 요청하면, 이는 0.4 바이트를 요청한 것이다. 이 사람은 아마도 400 메비바이트(mebibytes) (400Mi) 또는 400 메가바이트 (400M) 를 요청하고 싶었을 것이다.

 

 

 

 

YAML을 이용하여 request 리소스 pod 생성

# reqeust 리소스를 이용하여 cpu 0.25 코어 RAM 500M 생성 master@master:~$ cat request.yaml apiVersion: v1 kind: Pod metadata: ​​name: request spec: ​​containers: ​​- name: nginx ​​​​image: nginx ​​​​resources: ​​​​​​requests: ​​​​​​​​cpu: 250m ​​​​​​​​memory: 500Mi master@master:~$ master@master:~$ kubectl apply -f request.yaml pod/request created master@master:~$ master@master:~$ kubectl get pod NAME READY STATUS RESTARTS AGE volume-nginx 1/1 Running 1 2d4h env-pod 1/1 Running 1 2d3h request 1/1 Running 0 6s master@master:~$ master@master:~$ kubectl get pod request -oyaml apiVersion: v1 kind: Pod metadata: ​​annotations: ​​​​kubectl.kubernetes.io/last-applied-configuration: | ​​​​​​{"apiVersion":"v1","kind":"Pod","metadata":{"annotations":{},"name":"request","namespace":"default"},"spec":{"containers":[{"image":"nginx","name":"nginx","resources":{"requests":{"cpu":"250m","memory":"500Mi"}}}]}} ​​creationTimestamp: "2022-08-09T12:33:02Z" ​​name: request ​​namespace: default ​​resourceVersion: "15774" ​​selfLink: /api/v1/namespaces/default/pods/request ​​uid: 53aec9d6-6831-4d6e-b7ff-870a35eff92a spec: ​​containers: ​​- image: nginx ​​​​imagePullPolicy: Always ​​​​name: nginx ​​​​resources: ​​​​​​requests: ​​​​​​​​cpu: 250m ​​​​​​​​memory: 500Mi

 

 

YAML을 이용하여 limit 리소스 pod 생성

# limit 리소스를 이용하여 cpu 0.5 코어 RAM 1G 생성 master@master:~$ cat limits.yaml apiVersion: v1 kind: Pod metadata: ​​name: limit spec: ​​containers: ​​- name: nginx ​​​​image: nginx ​​​​resources: ​​​​​limits: ​​​​​​​cpu: 500m ​​​​​​​memory: 1Gi master@master:~$ master@master:~$ kubectl apply -f limits.yaml pod/limit created master@master:~$ master@master:~$ kubectl get pod NAME READY STATUS RESTARTS AGE volume-nginx 1/1 Running 1 2d4h env-pod 1/1 Running 1 2d4h request 1/1 Running 0 14m limit 1/1 Running 0 13m master@master:~$ master@master:~$ kubectl get pod limit -oyaml apiVersion: v1 kind: Pod metadata: ​​annotations: ​​​​kubectl.kubernetes.io/last-applied-configuration: | ​​​​​​{"apiVersion":"v1","kind":"Pod","metadata":{"annotations":{},"name":"limit","namespace":"default"},"spec":{"containers":[{"image":"nginx","name":"nginx","resources":{"limits":{"cpu":"500m","memory":"1Gi"}}}]}} ​​creationTimestamp: "2022-08-09T12:34:54Z" ​​name: limit ​​namespace: default ​​resourceVersion: "15864" ​​selfLink: /api/v1/namespaces/default/pods/limit ​​uid: 25e779dd-5f44-4c14-af31-108df5f8658d spec: ​​containers: ​​- image: nginx ​​​​imagePullPolicy: Always ​​​​name: nginx ​​​​resources: ​​​​​​limits: ​​​​​​​​cpu: 500m ​​​​​​​​memory: 1Gi ​​​​​​requests: ​​​​​​​​cpu: 500m ​​​​​​​​memory: 1Gi

 

 

 

 

 

 

 

 

 

참고자료

https://kubernetes.io/ko/docs/concepts/configuration/manage-resources-containers/

반응형
반응형

 

 

 

매개변수로 정보 전달하기

# Pod 생성하는 YAML파일 생성 master@master:~$ cat arg-pod.yaml apiVersion: v1 kind: Pod metadata: ​​name: arg-pod spec: ​​containers: ​​- name: ubuntu ​​​​image: ubuntu:18.04 ​​​​command: [ "echo" ] ​​​​args: [ "abc", "def" ] master@master:~$ master@master:~$ kubectl apply -f arg-pod.yaml pod/arg-pod created master@master:~$ master@master:~$ kubectl logs arg-pod abc def master@master:~$

 

 

환경변수 설정하기

# pod 생성을 위한 YAML 파일 생성 master@master:~$ cat env-pod.yaml apiVersion: v1 kind: Pod metadata: ​​name: env-pod spec: ​​containers: ​​- name: nginx ​​​​image: nginx ​​​​env: ​​​​- name: my_env ​​​​​​value: "this is jinsu nginx!" master@master:~$ master@master:~$ kubectl apply -f env-pod.yaml pod/env-pod created master@master:~$ master@master:~$ kubectl get pod NAME READY STATUS RESTARTS AGE volume-nginx 1/1 Running 0 41m env-pod 1/1 Running 0 44s master@master:~$ # exec 명령으로 env-pod 환경변수 확인 master@master:~$ kubectl exec env-pod -- printenv PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin HOSTNAME=env-pod my_env=this is jinsu nginx! KUBERNETES_PORT=tcp://10.43.0.1:443 KUBERNETES_PORT_443_TCP=tcp://10.43.0.1:443 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 NGINX_VERSION=1.23.1 NJS_VERSION=0.7.6 PKG_RELEASE=1~bullseye HOME=/root master@master:~$

 

 

 

 

 

 

 

 

참고자료

https://kubernetes.io/ko/docs/tasks/inject-data-application/_print/

 

 

 

반응형
반응형

 

 

 

볼륨(volume)

컨테이너 내의 디스크에 있는 파일은 임시적이며, 컨테이너에서 실행될 때 애플리케이션에 적지 않은 몇 가지 문제가 발생한다. 한 가지 문제는 컨테이너가 크래시될 때 파일이 손실된다는 것이다. kubelet은 컨테이너를 다시 시작하지만 초기화된 상태이다. 두 번째 문제는 Pod에서 같이 실행되는 컨테이너간에 파일을 공유할 때 발생한다. 쿠버네티스 볼륨 추상화는 이러한 문제를 모두 해결한다. Pod에 대해 익숙해지는 것을 추천한다

 

 

 

volume-pod 생성 

# YAML파일 생성 master@master:~$ cat volume-pod.yaml apiVersion: v1 kind: Pod metadata: ​​name: volume-nginx spec: ​​containers: ​​- name: jinsunginx ​​​​image: nginx ​​​​volumeMounts: ​​​​- mountPath: /test-volume ​​​​​​name: my-volume ​​volumes: ​​- name: my-volume ​​​​hostPath: ​​​​​​path: /home ​​​​​​type: Directory master@master:~$ # Pod 생성 master@master:~$ kubectl apply -f volume-pod.yaml pod/volume-nginx created

 

 

volume 연결 확인

# 로컬 디렉토리와 volume-nginx pod 디렉토리와 연결 확인 master@master:~$ kubectl exec volume-nginx -- ls -alh /test-volume/master total 64K drwxr-xr-x 6 1000 1000 4.0K Aug 7 07:54 . drwxr-xr-x 3 root root 4.0K Aug 6 16:27 .. -rw------- 1 1000 1000 1.2K Aug 7 07:13 .bash_history -rw-r--r-- 1 1000 1000 220 Apr 4 2018 .bash_logout -rw-r--r-- 1 1000 1000 3.8K Aug 7 05:36 .bashrc drwx------ 2 1000 1000 4.0K Aug 6 16:30 .cache drwx------ 3 1000 1000 4.0K Aug 6 16:30 .gnupg drwxrwxr-x 4 1000 1000 4.0K Aug 7 04:38 .kube -rw-r--r-- 1 1000 1000 807 Apr 4 2018 .profile drwx------ 2 1000 1000 4.0K Aug 6 16:28 .ssh -rw-r--r-- 1 1000 1000 0 Aug 7 03:44 .sudo_as_admin_successful -rw------- 1 1000 1000 8.8K Aug 7 07:54 .viminfo -rw-rw-r-- 1 1000 1000 155 Aug 7 07:14 jinsu2nginx.yaml -rw-rw-r-- 1 1000 1000 137 Aug 7 06:25 jinsunginx.yaml -rw-rw-r-- 1 1000 1000 270 Aug 7 07:54 volume-pod.yaml master@master:~$ master@master:~$ ls -al total 64 drwxr-xr-x 6 master master 4096 Aug 7 07:54 . drwxr-xr-x 3 root root 4096 Aug 6 16:27 .. -rw------- 1 master master 1165 Aug 7 07:13 .bash_history -rw-r--r-- 1 master master 220 Apr 4 2018 .bash_logout -rw-r--r-- 1 master master 3838 Aug 7 05:36 .bashrc drwx------ 2 master master 4096 Aug 6 16:30 .cache drwx------ 3 master master 4096 Aug 6 16:30 .gnupg -rw-rw-r-- 1 master master 155 Aug 7 07:14 jinsu2nginx.yaml -rw-rw-r-- 1 master master 137 Aug 7 06:25 jinsunginx.yaml drwxrwxr-x 4 master master 4096 Aug 7 04:38 .kube -rw-r--r-- 1 master master 807 Apr 4 2018 .profile drwx------ 2 master master 4096 Aug 6 16:28 .ssh -rw-r--r-- 1 master master 0 Aug 7 03:44 .sudo_as_admin_successful -rw------- 1 master master 8970 Aug 7 07:54 .viminfo -rw-rw-r-- 1 master master 270 Aug 7 07:54 volume-pod.yaml master@master:~$

 

 

 

 

참고자료

https://kubernetes.io/ko/docs/concepts/storage/volumes/

반응형
반응형

레이블과 셀렉터

레이블은 Pod와 같은 오브젝트에 첨부된 키와 값의 쌍이다. 레이블은 오브젝트의 특성을 식별하는 데 사용되어 사용자에게 중요하지만, 코어 시스템에 직접적인 의미는 없다. 레이블로 오브젝트의 하위 집합을 선택하고, 구성하는데 사용할 수 있다. 레이블은 오브젝트를 생성할 때에 붙이거나 생성 이후에 붙이거나 언제든지 수정이 가능하다. 오브젝트마다 키와 값으로 레이블을 정의할 수 있다. 오브젝트의 키는 고유한 값이어야 한다.

"metadata": { ​​"labels": { ​​​​"key1" : "value1", ​​​​"key2" : "value2" ​​} }

레이블은 UI와 CLI에서 효율적인 쿼리를 사용하고 검색에 사용하기에 적합하다. 식별되지 않는 정보는 어노테이션으로 기록해야 한다.

 

사용 동기

레이블을 이용하면 사용자가 간단하게 결합한 방식으로 조직 구조와 시스템 오브젝트를 매핑할 수 있으며, 클라이언트에 매핑 정보를 저장할 필요가 없다.

 

레이블 셀렉터

이름과 UID와 다르게 레이블은 고유하지 않다. 일반적으로 우리는 많은 오브젝트에 같은 레이블을 사용한다.

레이블 셀렉터를 통해 클라이언트와 사용자는 오브젝트를 식별할 수 있다. 레이블 셀렉터는 쿠버네티스 코어 그룹의 기본이다.

API는 현재 일치성 기준 과 집합성 기준 이라는 두 종류의 셀렉터를 지원한다. 레이블 셀렉터는 쉼표로 구분된 다양한 요구사항 에 따라 만들 수 있다. 다양한 요구사항이 있는 경우 쉼표 기호가 AND(&&) 연산자로 구분되는 역할을 하도록 해야 한다.

비어있거나 지정되지 않은 셀렉터는 상황에 따라 달라진다. 셀렉터를 사용하는 API 유형은 유효성과 의미를 따로 정의하여 정리해야 한다.

참고: 레플리카셋(ReplicaSet)과 같은 일부 API 유형에서 두 인스턴스의 레이블 셀렉터는 네임스페이스 내에서 겹치지 않아야 한다. 그렇지 않으면 컨트롤러는 상충하는 명령으로 보고, 얼마나 많은 복제본이 필요한지 알 수 없다.
주의: 일치성 기준과 집합성 기준 조건 모두에 대해 논리적인 OR (||) 연산자가 없다. 필터 구문이 적절히 구성되어 있는지 확인해야 한다.

 

labels 확인 

master@master:~$ kubectl get pod NAME READY STATUS RESTARTS AGE jinsunginx 1/1 Running 0 9s jinsu2nginx 1/1 Running 0 9s master@master:~$ master@master:~$ kubectl get pod -L run NAME READY STATUS RESTARTS AGE RUN jinsunginx 1/1 Running 0 2m58s jinsunginx jinsu2nginx 1/1 Running 0 2m58s jinsu2nginx master@master:~$ master@master:~$ kubectl get pod jinsunginx --show-labels NAME READY STATUS RESTARTS AGE LABELS jinsunginx 1/1 Running 0 3m21s run=jinsunginx master@master:~$

 

 

labels 추가 및 확인

# color를 red로 labels 설정 master@master:~$ cat jinsu2nginx.yaml apiVersion: v1 kind: Pod metadata: ​​labels: ​​​​run: jinsu2nginx ​​​​color: red ​​name: jinsu2nginx spec: ​​containers: ​​- name: nginx ​​​​image: nginx master@master:~$ # labels 확인 master@master:~$ kubectl get pod jinsu2nginx --show-labels NAME READY STATUS RESTARTS AGE LABELS jinsu2nginx 1/1 Running 0 27s color=red,run=jinsu2nginx master@master:~$

 

 

Pod edit으로 labels 수정

# kubectl edit pod로 color 오렌지색으로 labels 수정 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: ​​annotations: ​​​​kubectl.kubernetes.io/last-applied-configuration: | ​​​​​​{"apiVersion":"v1","kind":"Pod","metadata":{"annotations":{},"labels":{"run":"jinsunginx"},"name":"jinsunginx","names ​​creationTimestamp: "2022-08-07T07:08:05Z" ​​labels: ​​​​color: orange ​​​​run: jinsunginx ​​name: jinsunginx ​​namespace: default ​​resourceVersion: "7343" ​​selfLink: /api/v1/namespaces/default/pods/jinsunginx ​​uid: 22d83e8b-4d1e-4072-a09c-b19eabc47a95" ... # color labels 수정 확인 master@master:~$ kubectl get pod jinsunginx --show-labels NAME READY STATUS RESTARTS AGE LABELS jinsunginx 1/1 Running 0 12m color=orange,run=jinsunginx master@master:~$

 

 

labels 필터링으로 찾기

aster@master:~$ kubectl get pod -l run NAME READY STATUS RESTARTS AGE jinsu2nginx 1/1 Running 0 7m15s jinsunginx 1/1 Running 0 14m master@master:~$ master@master:~$ kubectl get pod -l run=jinsunginx NAME READY STATUS RESTARTS AGE jinsunginx 1/1 Running 0 15m master@master:~$

 

 

node selector 이용하여 disktype 구분

master@master:~$ kubectl label node master disktype=ssd # node/master labeld master@master:~$ master@master:~$ cat << EOF | kubectl apply -f - apiVersion: v1 kind: Pod metadata: ​​labels: ​​​​run: jinsunginx ​​name: jinsunginx spec: ​​containers: ​​- name: jinsunginx ​​​​image: nginx ​​nodeSelector: ​​​​disktype: ssd EOF master@master:~$

 

 

 

 

 

참고자료

https://kubernetes.io/ko/docs/concepts/overview/working-with-objects/labels/

반응형
반응형

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/

 

 

 

반응형
반응형

 

 

Docker

Ubuntu 환경에서 Docker 명령어 사용하기


Ubuntu 20.04.4 LTS 환경으로 테스트 진행

 

 

 

 

 

Dockerfile을 생성하여 파일을 docker build 하려고 할 때 아래와 같은 에러가 발생합니다.

원인을 몰라 한참 찾아봤었는데 처음에는 뭐가 문제인지 잘몰랐었는데 Dockerfile을 만들어서

build 해줄 때 filename을 Dockerfile 이라고 만들어줘야 하는 거였다.

 

Dockerfile을 만들때에는 디렉토리를 새로만들고 해당 디렉토리로 들어가서 build 해줘야한다.

 

나는 바보인가보다 ㅠ

 

unable to prepare context: unable to evaluate symlinks in Dockerfile path:

 

 

$ sudo docker build -t kubers:1 . unable to prepare context: unable to evaluate symlinks in Dockerfile path: lstat /home/djwlstn123/k8s/Dockerfile: no such file or directory EX) $ sudo docker build -t kuard-amd64:1 . Sending build context to Docker daemon 2.048kB Step 1/3 : FROM alpine

 

 

반응형

+ Recent posts