개요

1. 헬름 템플릿 변수 파일 사용하기

2. 리소스 Requests/Limits 이해


1. 헬름 템플릿 변수 파일 사용하기

vi templates/deployment.yaml

{{- if .Values.resources }}
resources: {{- toYaml .Values.resources | nindent 12 }}
{{- else if ne .Values.resourcesPreset "none" }}
resources: {{- include "common.resources.preset" (dict "type" .Values.resourcesPreset) | nindent 12 }}

 

{{- if .Values.resources }}

if 문을 사용해 resources 변수가 정의돼 있으면 해당 변수를 사용하도록 설정할 수 있다.

 

{{- toYaml .Values.resources | nindent 12 }}

toYaml 함수를 사용해 해당 변수의 내용을 들여쓰기 12칸 형식의 yaml 형식으로 전환한다.


2. 리소스 Requests/Limits 이해

같은 노드에 실행 중인 여러 파드는 동일한 호스트 노드의 자원을 공유하므로 특정 파드가 자원을 많이 사용하면 공통으로 사용 중인 노드 자원이 줄어들어 다른 파드의 성능에 영향을 끼친다.

이러한 상황에 대비해 파드가 사용 가능한 자원을 제한 할 수 있는 옵션이다.

 

Limits(제한)

resources:

  limits:

    cpu: 1000m

    memory: 500Mi

설정은 해당 파드가 1 CPU(1,000m은 1 CPU), 512Mi 메모리 이상의 자원을 사용하지 못하게 제한.


Request(요청량)

resources:

  requests:

    cpu: 100m

    memory: 128Mi

처음 노드에 파드를 할당할 때 해당 요청량(Request) 이상의 여유 자원이 있는 노드에 파드를 할당하게 하는 옵션이다.
파드가 배치된 이 후 각 파드 간 자원 사용량이 증가해서 노드에서 할당 가능한 자원 이상을 사용해 자원 경합이 발생하면 파드는 Requests에서 할당한 자원만큼 사용이 가능하도록 보장받는다.

파드가 보장받을 수 있는 자원 요청량으로 이해하면 된다.

 

예제

apiVersion: v1
kind: Pod
metadata:
  name: memory-demo-1
spec:
  containers:
  - name: memory-demo-1
    image: polinux/stress
    resources:
      requests:
        memory: "1Gi"
      limits:
        memory: "2Gi"
    command: ["stress"]
    args: ["--vm", "1", "--vm-bytes", "2500M", "--vm-hang", "1"]

 

kubectl apply -f oom-demo.yaml

허용 한계는 2기가인데 2500m 메모리를 스트레스 줘서 OOM이 발생한다.

k get pod -o wide
NAME                    READY   STATUS      RESTARTS      AGE   IP              NODE           NOMINATED NODE   READINESS GATES
memory-demo-1           0/1     OOMKilled   2 (21s ago)   35s   10.10.180.241   worker-node1   <none>           <none>

 

kubectl describe pod memory-demo-1

  Normal   Created    13s (x2 over 19s)  kubelet            Created container memory-demo-1
  Normal   Started    13s (x2 over 18s)  kubelet            Started container memory-demo-1
  Normal   Pulled     13s                kubelet            Successfully pulled image "polinux/stress" in 1.624650799s (1.624671461s including waiting)
  Warning  BackOff    11s                kubelet            Back-off restarting failed container memory-demo-1 in pod memory-demo-1_nginx(c3c631f8-842a-4ae5-90b3-d2f94a4ca5fb)

 

# 파드에 접속

kubectl exec -it memory-demo-1 -- bash

kubectl exec -it memory-demo-1 -- /bin/sh

kubectl exec -it memory-demo-1 -- /bin/bash

 

# 2900메가까지 스트레스 주기
stress --vm 1 --vm-byte 2900M --vm-hang 1

 

# 삭제하기

kubectl delete pod --all

kubectl delete deployments.apps --all

개요

1.헬름을 이용해서 Nginx 설치하기

2. startup probe, liveness probe, readiness probe 알아보기


helm repo add bitnami https://charts.bitnami.com/bitnami 

 

helm repo ls
NAME       URL
github-ksh https://sunghyun-kim-nhn.github.io/k8s-study-helm
bitnami    https://charts.bitnami.com/bitnami

 

helm search repo nginx
NAME                             CHART VERSION APP VERSION DESCRIPTION
bitnami/nginx                    15.11.0       1.25.4      NGINX Open Source is a web server that can be a...
bitnami/nginx-ingress-controller 10.4.0        1.9.6       NGINX Ingress Controller is an Ingress controll...
bitnami/nginx-intel              2.1.15        0.4.9       DEPRECATED NGINX Open Source for Intel is a lig...

 

helm pull nginx

nginx 헬름 차트가 받아진다.

-rw-r--r--@  1 nhn  staff   231B  2 17 01:25 Chart.lock
-rw-r--r--@  1 nhn  staff   1.0K  2 17 01:25 Chart.yaml
-rw-r--r--@  1 nhn  staff    69K  2 17 01:25 README.md
drwxr-xr-x@  3 nhn  staff    96B  2 19 17:35 charts
drwxr-xr-x@ 17 nhn  staff   544B  2 19 17:35 templates
-rw-r--r--@  1 nhn  staff   3.3K  2 17 01:25 values.schema.json
-rw-r--r--@  1 nhn  staff    41K  2 17 01:25 values.yaml
 nhn@AL01600616  ~/kube-study/nginx  ls templates
NOTES.txt                   extra-list.yaml             ingress.yaml                prometheusrules.yaml        servicemonitor.yaml
_helpers.tpl                health-ingress.yaml         networkpolicy.yaml          server-block-configmap.yaml svc.yaml
deployment.yaml             hpa.yaml                    pdb.yaml                    serviceaccount.yaml         tls-secrets.yaml

 

kubectl create ns nginx

kubectl ns nginx

 

helm install nginx -f my-values.yaml .

현재 위치의 헬름 차트를 이용해서 설치한다.

k get pod -n nginx -o wide
NAME                    READY   STATUS    RESTARTS   AGE
nginx-6478d87dc-8tqlg   1/1     Running   0          8m14s   10.10.180.240   worker-node1   <none>           <none>
nginx-6478d87dc-tw7r2   1/1     Running   0          8m14s   10.10.180.239   worker-node1   <none>           <none>

 nhn@AL01600616  ~/kube-study/nginx  helm ls
WARNING: Kubernetes configuration file is group-readable. This is insecure. Location: /Users/nhn/.kube/config
WARNING: Kubernetes configuration file is world-readable. This is insecure. Location: /Users/nhn/.kube/config
NAME 	NAMESPACE	REVISION	UPDATED                             	STATUS  	CHART        	APP VERSION
nginx	nginx    	1       	2024-02-19 17:43:27.287431 +0900 KST	deployed	nginx-15.11.0	1.25.4

 

k get all

k get all
NAME                        READY   STATUS    RESTARTS   AGE
pod/nginx-6478d87dc-8tqlg   1/1     Running   0          8m51s
pod/nginx-6478d87dc-tw7r2   1/1     Running   0          8m51s

NAME            TYPE           CLUSTER-IP       EXTERNAL-IP   PORT(S)        AGE
service/nginx   LoadBalancer   10.105.188.107   <pending>     80:31752/TCP   8m51s

NAME                    READY   UP-TO-DATE   AVAILABLE   AGE
deployment.apps/nginx   2/2     2            2           8m51s

NAME                              DESIRED   CURRENT   READY   AGE
replicaset.apps/nginx-6478d87dc   2         2         2       8m51s

 

k get deploy,svc,configmap

k get deploy,svc,configmap
NAME                    READY   UP-TO-DATE   AVAILABLE   AGE
deployment.apps/nginx   2/2     2            2           9m55s

NAME            TYPE           CLUSTER-IP       EXTERNAL-IP   PORT(S)        AGE
service/nginx   LoadBalancer   10.105.188.107   <pending>     80:31752/TCP   9m55s

NAME                         DATA   AGE
configmap/kube-root-ca.crt   1      10m

 

 

## NGINX containers' startup probe.

  • startupProbe는 컨테이너가 처음 시작될 때만 실행되는 프로브입니다. 즉, 컨테이너가 처음 시작될 때만 실행되고 그 이후에는 실행되지 않습니다.
  • 이 프로브는 애플리케이션이 초기화되는 동안 컨테이너의 상태를 확인하는 데 사용됩니다. 예를 들어, 애플리케이션이 데이터베이스 스키마를 초기화하는 동안에는 startupProbe가 사용될 수 있습니다.

## ref: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#container-probes
## @param startupProbe.enabled Enable startupProbe
## @param startupProbe.initialDelaySeconds Initial delay seconds for startupProbe
## @param startupProbe.periodSeconds Period seconds for startupProbe
## @param startupProbe.timeoutSeconds Timeout seconds for startupProbe
## @param startupProbe.failureThreshold Failure threshold for startupProbe
## @param startupProbe.successThreshold Success threshold for startupProbe
##
startupProbe:
  enabled: false
  initialDelaySeconds: 30
  timeoutSeconds: 5
  periodSeconds: 10
  failureThreshold: 6
  successThreshold: 1


## NGINX containers' liveness probe.

  • livenessProbe는 컨테이너가 현재 실행 중인지 확인하는 데 사용됩니다. 즉, 컨테이너가 계속 실행 중인지 여부를 확인하여 필요에 따라 다시 시작하거나 컨테이너를 복구할 수 있도록 도와줍니다.
  • 이 프로브는 컨테이너가 정상적으로 작동하고 있는지 주기적으로 확인하고, 컨테이너가 죽었을 때 이를 감지하여 Kubernetes가 해당 컨테이너를 재시작하도록 유도합니다.

## ref: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#container-probes
## @param livenessProbe.enabled Enable livenessProbe
## @param livenessProbe.initialDelaySeconds Initial delay seconds for livenessProbe
## @param livenessProbe.periodSeconds Period seconds for livenessProbe
## @param livenessProbe.timeoutSeconds Timeout seconds for livenessProbe
## @param livenessProbe.failureThreshold Failure threshold for livenessProbe
## @param livenessProbe.successThreshold Success threshold for livenessProbe
##
livenessProbe:
  enabled: true
  initialDelaySeconds: 30
  timeoutSeconds: 5
  periodSeconds: 10
  failureThreshold: 6
  successThreshold: 1


## NGINX containers' readiness probe.

  • readinessProbe는 컨테이너가 요청을 처리할 수 있는 상태인지를 확인하는 데 사용됩니다. 즉, 컨테이너가 준비되었는지를 확인하고, 서비스 트래픽을 전달할 준비가 되었는지를 결정합니다.
  • 이 프로브는 컨테이너가 시작되고 서비스가 정상적으로 제공될 수 있을 때까지 기다릴 수 있도록 합니다. 만약 컨테이너가 아직 준비되지 않았다면 해당 컨테이너에 트래픽을 전달하지 않습니다.

## ref: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#container-probes
## @param readinessProbe.enabled Enable readinessProbe
## @param readinessProbe.initialDelaySeconds Initial delay seconds for readinessProbe
## @param readinessProbe.periodSeconds Period seconds for readinessProbe
## @param readinessProbe.timeoutSeconds Timeout seconds for readinessProbe
## @param readinessProbe.failureThreshold Failure threshold for readinessProbe
## @param readinessProbe.successThreshold Success threshold for readinessProbe
##
readinessProbe:
  enabled: true
  initialDelaySeconds: 5
  timeoutSeconds: 3
  periodSeconds: 5
  failureThreshold: 3
  successThreshold: 1


- startupProbe는 초기화 중에만 실행되고, 
- livenessProbe는 컨테이너의 실행 여부를 주기적으로 확인하며, 
- readinessProbe는 컨테이너가 서비스 요청을 처리할 준비가 되었는지를 확인합니다. 
이들은 모두 애플리케이션을 관리하고 안정적으로 실행하는 데 중요한 도구입니다.

쿠버네티스는 리소스가 여러 개 필요한 경우가 많다.

 

  • 파드 노출을 담당하는 서비스(Service)
  • 애플리케이션 설정에 관련된 컨피그맵(ConfigMap)
  • 기밀 정보를 다루는 시크릿(Secret)

 

다양한 리소스를 각각 관리하지 않고 하나의 패키지로 관리하는 도구가 헬름(Helm)이다.

 

주요 구성 요소

  • 헬름 차트(Helm Chart):
    • 여러 리소스의 묶음
    • 헬름 차트 하나로 여러 어플리케이션을 일괄 설치 가능
    • Chart.yaml: 차트에 대한 정보가 담긴 yaml 파일
    • values.yaml: 차트의 기본 템플릿 변수 파일
    • charts/: 차트에 종속된 차트들을 포함하는 디렉터리
    • crds/: 커스텀 자원 정의
    • templates/: values 파일과 같이 유효한 쿠버네티스 매니페스트 파일을 생성하는 템플릿
  • 헬름 리포지토리(Helm Repository)
    • 헬름 차트를 저장하고 공유하는 저장소
    • yum과 유사
    • 많은 솔루션 업체들이 직접 헬름 리포지토리를 제공함
    • ex) ArtifactHub 다양한 헬름 차트 허브 제공
  • 헬름 템플릿(Helm Template)
    • 설치와 관련한 파일들 관리한다.
    • 일정한 형식 또는 포맷을 의미
    • 이름, 날짜 등의 특정 변수만 수정하여 해당 파일을 사용할 수 있다.
    • 여러 템플릿 파일에서 공통으로 사용하는 변수를 단일 values.yaml 파일에서 관리한다.
      해당 파일만 수정하면 전체 템플릿 파일에서 사용하는 변수를 한꺼번에 수정할 수 있다.
    • Ex) favoriteDrink: coffee
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ .Release.Name }}-configmap
data:
  myvalue: "Hello world"
  drink: {{ .Value.favoriteDrink }}

helm install geared-marsupi ./mychart --dry-run --debug

이렇게 치면 drink에 coffee라는 변수가 들어간 모습을 볼 수 있다.

 

 

헬름 설치

curl -fsSL -o get_heml.sh https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3

./get_heml.sh
Downloading https://get.helm.sh/helm-v3.14.1-darwin-arm64.tar.gz
Verifying checksum... Done.
Preparing to install helm into /usr/local/bin
Password:
helm installed into /usr/local/bin/helm
 nhn@AL01600616  ~  helm version
WARNING: Kubernetes configuration file is group-readable. This is insecure. Location: /Users/nhn/.kube/config
WARNING: Kubernetes configuration file is world-readable. This is insecure. Location: /Users/nhn/.kube/config
version.BuildInfo{Version:"v3.13.1", GitCommit:"3547a4b5bf5edb5478ce352e18858d8a552a4110", GitTreeState:"clean", GoVersion:"go1.21.3"}

 

  • helm repo add: 애플리케이션 설치에 사용되는 헬름 리포지토리를 로컬 환경에 추가한다.
  • helm pull: 헬름 차트 파일을 로컬 호스트로 내려받는다.
  • cp values.yaml my-values.yaml: 원본 템플릿 변수 파일의 이력을 관리하기 위해 새 파일로 복사
  • helm install {helm name} -f my-values.yaml: 애플리케이션 설치
  • helm ls: 헬름 차트 목록 확인
  • helm get manifest: 주로 디버깅 용도로 사용하며, 현재 실행 중인 헬름 차트의 전체 yaml 파일 목록 및 상세 설정을 확인할 수 있다.
  • helm upgrade: 기존 헬름 차트의 변수 등을 수정해서 재배포한다.
  • helm delete: 헬름 차트를 삭제한다.

+ Recent posts