쿠버네티스 패턴

created : Tue, 16 Aug 2022 10:56:05 +0900
modified : Fri, 26 Aug 2022 16:08:59 +0900
kubernetes k8s book

1장 개요

클라우드 네이티브로 가는길

분산 기본 요소

개념로컬 기본 요소분산 기본 요소
캡슐화 동작클래스컨테이너 이미지
인스턴스화 동작객체컨테이너
재사용 단위Jar 파일컨테이너 이미지
컴포지션포함 관계사이드카 패턴
상속확장 관계FROM 으로 부모 이미지 상속
배포 단위.jar/.war/.earpod
빌드타임/런타임 격리모듈, 패키지, 클래스namespace, pod, container
초기화 필요조건Constructor초기화 컨테이너
초기화 직 후 트리거Init methodpostStart
삭제 직전 트리거Destroy methodpreStop
정리 절차finalize(), shutdown hookDefer 컨테이너
비동기 & 병렬 칫행ThreadPoolExecutor, ForkJoinPoolJob
주기적 작업Timer, ScheduleExecutorServiceCronJob
백그라운드 작업Deamon ThreadDeamonSets
설정관리System.getenv(), PropertiesConfigMap, Secret

컨테이너

파드

서비스

레이블

어노테이션

네임스페이스

1부 기본 패턴

2장 예측 범위 내의 요구사항

런타임 의존성

자원 프로파일

파드 우선순위

apiVersion: scheduling.k8s.io/v1
kind: PrioirtyClass
metadata:
  name: high-priority
value: 1000
globalDefault: flase
description: "This is a very high priority Pod class"
---
apiVersion: v1
kind: Pod
metadata:
  name: random-generator
  labels:
    env: random-generator
spec:
  containers:
  - image: k8spatterns/random-generator:1.0
    name: random-generator
  priorityClassName: high-prioirty

프로젝트 자원

3장 선언적 배포

고정 배포

블루-그린

카나리아

4장 정상상태 점검

Liveness probe

apiVersion: v1
kind: Pod
metadata:
  name: pod-with-liveness-check
spec:
  containers:
  - image: k8spatterns/random-generator:1.0
    name: random-generator
    env:
    - name: DELAY_STARTUP
      value: "20"
    ports:
    - containerPort: 8080
    protocol: TCP
    livenessProbe:
      httpGet:
        path: /actuator/health
        port: 8080
      initialDelaySeconds: 30

Readiness probe

Others

5장 수명주기 관리

apiVersion: v1
kind: Pod
metatdata:
  name: hooks
spec:
  containers:
  - image: k8spatterns/random-generator:1.0
  name: random-generator
  lifecycle:
    postStart:
      exec:
        command:
        - sh
        - -c
        - sleep 30 && echo "Wake up!" > /tmp/postStart_done
    preStop:
      httpGet:
        port: 8080
        path: /shutdown
측면수명주기 훅초기화 컨테이너
활성화 단계컨테이너 수명주기 단계파드 수명주기 단계
시작 단계 동작postStart 명령어실행될 초기화 컨테이너 목록
종료 단계 동작preStop 명령어X
타이밍(Timing) 보장postStart 명령은 컨테이너의 ENTRYPOINT 와 동시에 실행애플리케이션 컨테이너가 시작되기 전에 모든 초기화 컨테이너는 성공적으로 종료가 완료되어야 한다.
사용 사례컨테이너별로 트고하된 중요하지 않은 시작/정리 종료를 실행컨테이너를 사용해 워크플로우 같은 순차적 작업을 수행. 작업 실행을 위해 컨테이너를 재사용

6장 자동 배치

Node Affinity

Pod Affinity

Taint 와 Toleration

Descheduler

2부 행동 패턴

7장 배치 잡

8장 주기적 잡

apiVersion: batch/v1
kind: CronJob
metadata:
  name: random-generator
spec:
  schedule: "*/3 * * * *"
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: random-generator
            image: k8spatterns/random-generator:1.0
            command:
            - "java"
            - "-cp"
            - "/"
            - "RandomRunner"
            - "/numbers.txt"
            - "10000"
          restartPolicy: OnFailure

9장 데몬 서비스

10장 싱글톤 서비스

애플리케이션 외부 잠금

애플리케이션 내부 잠금

PodDisruptionBudget

apiVersion: policy/v1
kind: PodDistruptionBudget
metadata:
  name: random-generator-pdb
spec:
  selector:
    matchLabels:
      app: random-generator
  minAvailable: 2

11장 스테이트풀 서비스

apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: rg
spec:
  serviceName: random-generator
  replicas: 2
  selector:
    matchLabels:
      app: random-generator
  template:
    metadata:
      labels:
        app: random-generator
    spec:
      containers:
      - image: k8spatterns/random-generator:1.0
        name: random-generator
        ports:
        - containerPort: 8080
          name: http
        volumeMounts:
        - name: logs
          mountPath: /logs
  volumeClaimTemplates:
  - metadata:
      name: logs
    spec:
      accessModes: [ "ReadWriteOnce" ]
      resources:
        requests:
          storage: 10Mi

네트워크

순서성

개인적인 궁금점

기타 기능

12장 서비스 디스커버리

내부 디스커버리

수동 서비스 디스커버리

클러스터 외부의 서비스 디스커버리

어플리케이션 계층 서비스 디스커버리

개인생각

13장 자기 인식

apiVersion: v1
kind: Pod
metadata:
  name: kubernetes-downwardapi-volume-example
  labels:
    zone: us-est-coast
    cluster: test-cluster1
    rack: rack-22
  annotations:
    build: two
    builder: john-doe
spec:
  containers:
    - name: client-container
      image: k8s.gcr.io/busybox
      command: ["sh", "-c"]
      args:
      - while true; do
          if [[ -e /etc/podinfo/labels ]]; then
            echo -en '\n\n'; cat /etc/podinfo/labels; fi;
          if [[ -e /etc/podinfo/annotations ]]; then
            echo -en '\n\n'; cat /etc/podinfo/annotations; fi;
          sleep 5;
        done;
      volumeMounts:
        - name: podinfo
          mountPath: /etc/podinfo
  volumes:
    - name: podinfo
      downwardAPI:
        items:
          - path: "labels"
            fieldRef:
              fieldPath: metadata.labels
          - path: "annotations"
            fieldRef:
              fieldPath: metadata.annotations

3부 구조 패턴

14장 초기화 컨테이너

15장 사이드카

16장 어댑터

17장 앰배서더(Ambassador)

4부 설정 패턴

18장 EnvVar 설정

apiVersion: v1
kind: Pod
metadata:
  name: random-generator
spec:
  containers:
  - image: k8spatterns/random-generator:1.0
    name: random-generator
    env:
    - name: LOG_FILE
      value: /tmp/random.log
    - name: PATTERN
      valueFrom:
        configMapKeyRef:
          name: random-generator-config
          key: pattern
    - name: SEED
      valueFrom:
        secretKeyRef:
          name: random-generator-secret
          key: seed

19장 설정 자원

20장 불변 설정

21장 설정 템플릿

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  labels:
    example: cm-template
  name: widfly-cm-template
spec:
  replicas: 1
  template:
    metadata:
      labels:
        example: cm-template
    spec:
      initContainers:
      - image: k8spatterns/example-config-cm-template-init
        name: init
        volumeMounts:
        - mountPath: "/params"
          name: wildfly-parameters
        - mountPath: "/out"
          name: widfly-config
      containers:
      - image: jboss/wildfly:10.1.0.Final
        name: server
        command:
        - "/opt/jboss/wildfly/bin/standalone.sh"
        - "-Djboss.server.config.dir=/config"
        ports:
        - containerPort: 8080
          name: http
          protocol: TCP
        volumeMounts:
        - mountPath: "/config"
          name: wildfly-config
        volumes:
        - name: wildfly-parameters
          configMap:
            name: wildfly-parameters
        - name: wildfly-config
          emptyDir: {}

5부 고급 패턴

22장 컨트롤러

23장 오퍼레이터

24장 탄력적스케일

kubectl autoscale deployment <deployment name> --cpu-percent=50 --min=1 --max=5
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: random-generator
  spec:
    minReplicas: 1
    maxReplicas: 5
    scaleTargetRef:
      apiVersion: apps/v1
      kind: Deployment
      name: random-generator
    metrics:
    - resource:
        name: cpu
        target:
          averageUtilization: 50
          type: Utilization
      type: Resource

수직 Pod Autoscaling

apiVersion: autoscaling.k8s.io/v1
kind: VerticalPodAutoscaler
metadata:
  name: my-app-vpa
spec:
  targetRef:
    apiVersion: "apps/v1"
    kind:       Deployment
    name:       my-app
  updatePolicy:
    updateMode: "Auto"

25장 이미지 빌더

apiVersion: v1
kind: BuildConfig
metadata:
  name: runtime
spec:
  source:
    images:
    - from:
        kind: ImageStreamTag
        name: random-generator-build:latest
      paths:
      - sourcePath: /deployments/.
        destinationDir: "."
    dockerfile: |-
      FROM openjdk:8-alpine
      COPY *.jar /
      CMD java -jar /*.jar      
  strategy:
    type: Docker
  output:
    to:
      kind: ImageStreamTag
      name: random-generator:latest
  triggers:
  - imageChange:
      automatic: true
      from:
        kind: ImageStreamTag
        name: random-gnerator-build:latest
    type: ImageChange

다읽은 후기