목차

107. Demo: Encrypting Secret Data at Rest

108. Scale Applications

109. Multi Container PODS

110.Practice Test - Multi Container PODs

112. Multi-container PODs Design Patterns

113. InitContainers

114. Practice Test - Init Containers

116. Self Healing Applications

 

 

107. Demo: Encrypting Secret Data at Rest

Encrypting Secret Data at Rest | Kubernetes

 

Encrypting Secret Data at Rest

This page shows how to enable and configure encryption of secret data at rest. Before you begin You need to have a Kubernetes cluster, and the kubectl command-line tool must be configured to communicate with your cluster. It is recommended to run this tuto

kubernetes.io

 

secret 에서는 base64 가 기본적인 인코딩 규칙

etcd server 에 데이터가 어떻게 저장되는가? 

secret을 만든 후 etcd는 어떤식으로 정보를 가지고 있을까 ?

 

etcdctl 명령어를 쓸려면

apt-get install etcd-client

설치한다. 

etcd server도 pod 이다. 

kubectl get pods -n kube-system

으로  pod 확인

ETCDCTL_API=3 etcdctl \
   --cacert=/etc/kubernetes/pki/etcd/ca.crt   \
   --cert=/etc/kubernetes/pki/etcd/server.crt \
   --key=/etc/kubernetes/pki/etcd/server.key  \
   get /registry/secrets/default/secret1 | hexdump -C

secret1 은 secret 이름 쓰면된다. 

해당 명령어를 쓰면 secret 안의 내용을 다 볼 수 있다. ( hexdump 옵션없이 하면)

실제로는 hexdump 16진법으로 etcd server에 저장된다. 

자세히 보면 여전히 secret 내용을 볼 수 있다. 

ps -aux | grep kube-api | grep "encryption-provider-config"

encryption-provider-config 가 있는지 확인한다.

ls /etc/kubernetes/manifests

해당 경로에 kube-apiserver.yaml 이 있는지 확인

yaml 파일안에 encryption option 이 있는 지 확인

 

apiVersion: apiserver.config.k8s.io/v1
kind: EncryptionConfiguration
resources:
  - resources:
      - secrets
    providers:
      - identity: {}
      - aesgcm:
          keys:
            - name: key1
              secret: c2VjcmV0IGlzIHNlY3VyZQ==
            - name: key2
              secret: dGhpcyBpcyBwYXNzd29yZA==
      - aescbc:
          keys:
            - name: key1
              secret: c2VjcmV0IGlzIHNlY3VyZQ==
            - name: key2
              secret: dGhpcyBpcyBwYXNzd29yZA==
      - secretbox:
          keys:
            - name: key1
              secret: YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXoxMjM0NTY=

Encryption config 파일을 만든다.

 resource 가 암호화할 대상

provider 엔 어떤 암호화 방식을 쓸 것인지 알려줌 

암호화 알고리즘.

identity 는 암호화 x 

keys는 암호화에 필요한 랜덤 인자 ?

 

providers 에 첫번째에 있는것을 선택한다 

 

Create new secret

 

1.Generate a 32-byte random key and base64 encode it. If you're on Linux or macOS, run the following command:

head -c 32 /dev/urandom | base64

랜덤 키값 얻기 (sdfasdf sdf 키값이 나온다.)

 

2. Place that value in the secret field of the EncryptionConfiguration struct.

apiVersion: apiserver.config.k8s.io/v1
kind: EncryptionConfiguration
resources:
  - resources:
      - secrets
    providers:
      - aescbc:
          keys:
            - name: key1
              secret: <BASE 64 ENCODED SECRET>
      - identity: {}

키값을 secret 부분에 기입한다. 

 

3. Set the --encryption-provider-config flag on the kube-apiserver to point to the location of the config file.

You will need to mount the new encryption config file to the kube-apiserver static pod. Here is an example on how to do that:

 

  1. Save the new encryption config file to /etc/kubernetes/enc/enc.yaml on the control-plane node.

/etc/kubernetes/enc/ 로컬 디렉토리 생성후 enc.yaml 파일 넣기

 

 2. Edit the manifest for the kube-apiserver static pod: /etc/kubernetes/manifests/kube-apiserver.yaml similarly to this:

 

/etc/kubernetes/manifests/kube-apiserver.yaml 파일 수정

 

apiVersion: v1
kind: Pod
metadata:
  annotations:
    kubeadm.kubernetes.io/kube-apiserver.advertise-address.endpoint: 10.10.30.4:6443
  creationTimestamp: null
  labels:
    component: kube-apiserver
    tier: control-plane
  name: kube-apiserver
  namespace: kube-system
spec:
  containers:
  - command:
    - kube-apiserver
    ...
    - --encryption-provider-config=/etc/kubernetes/enc/enc.yaml  # <-- 이거 추가
    volumeMounts:
    ...
    - name: enc                           # <-- add this line
      mountPath: /etc/kubernetes/enc      # <-- add this line
      readonly: true                      # <-- add this line
    ...
  volumes:
  ...
  - name: enc                             # <-- add this line
    hostPath:                             # <-- add this line
      path: /etc/kubernetes/enc           # <-- add this line
      type: DirectoryOrCreate             # <-- add this line
  ...

4 . Restart your API server.

 

이제 secret 을 생성하고 

ETCDCTL_API=3 etcdctl \
   --cacert=/etc/kubernetes/pki/etcd/ca.crt   \
   --cert=/etc/kubernetes/pki/etcd/server.crt \
   --key=/etc/kubernetes/pki/etcd/server.key  \
   get /registry/secrets/default/secret1 | hexdump -C

etcdctl 명령어로 확인하면

00000000  2f 72 65 67 69 73 74 72  79 2f 73 65 63 72 65 74  |/registry/secret|
00000010  73 2f 64 65 66 61 75 6c  74 2f 73 65 63 72 65 74  |s/default/secret|
00000020  31 0a 6b 38 73 3a 65 6e  63 3a 61 65 73 63 62 63  |1.k8s:enc:aescbc|
00000030  3a 76 31 3a 6b 65 79 31  3a c7 6c e7 d3 09 bc 06  |:v1:key1:.l.....|
00000040  25 51 91 e4 e0 6c e5 b1  4d 7a 8b 3d b9 c2 7c 6e  |%Q...l..Mz.=..|n|
00000050  b4 79 df 05 28 ae 0d 8e  5f 35 13 2c c0 18 99 3e  |.y..(..._5.,...>|
[...]
00000110  23 3a 0d fc 28 ca 48 2d  6b 2d 46 cc 72 0b 70 4c  |#:..(.H-k-F.r.pL|
00000120  a5 fc 35 43 12 4e 60 ef  bf 6f fe cf df 0b ad 1f  |..5C.N`..o......|
00000130  82 c4 88 53 02 da 3e 66  ff 0a                    |...S..>f..|
0000013a

etcd 에서도 완벽히 암호화되었다. 

 

 

108. Scale Applications

We have already discussed about scaling applications in the Deployments and Rolling updates and Rollback sections.

 

 

109. Multi Container PODS

마이크로서비스

msa 를 활용함으로써 service를 확대, 축소가 용이해졌다. 

두가지 서비스가 같이 연동되어야하는 경우가 있다.

이렇게 합치는 느낌?
multi container pods 는 여러가지 서비스를 하나처럼 묶어서 사용한다.

containers 에 하나 더 추가하면된다. 

 

 

110. Practice Test - Multi Container PODs

1.

Identify the number of containers created in the red pod.

 

2.

Identify the name of the containers running in the blue pod.

3.

Create a multi-container pod with 2 containers. Use the spec given below.

If the pod goes into the crashloopbackoff then add the command sleep 1000 in the lemon container.

  • Name: yellow

  • Container 1 Name: lemon

  • Container 1 Image: busybox

  • Container 2 Name: gold

  • Container 2 Image: redis

     

     

4.

We have deployed an application logging stack in the elastic-stack namespace. Inspect it.

Before proceeding with the next set of questions, please wait for all the pods in the elastic-stack namespace to be ready. This can take a few minutes.

 

5.

Once the pod is in a ready state, inspect the Kibana UI using the link above your terminal. There shouldn't be any logs for now.

We will configure a sidecar container for the application to send logs to Elastic Search.

 

NOTE: It can take a couple of minutes for the Kibana UI to be ready after the Kibana pod is ready.

You can inspect the Kibana logs by running:
kubectl -n elastic-stack logs kibana

6.

Inspect the app pod and identify the number of containers in it.

It is deployed in the elastic-stack namespace.

7.

The application outputs logs to the file /log/app.log. View the logs and try to identify the user having issues with Login.

Inspect the log file inside the pod.

kubectl logs -f app

 

8.

Edit the pod to add a sidecar container to send logs to Elastic Search. Mount the log volume to the sidecar container.

Only add a new container. Do not modify anything else. Use the spec provided below.

Note: State persistence concepts are discussed in detail later in this course. For now please make use of the below documentation link for updating the concerning pod.

 

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

  • Name: app

  • Container Name: sidecar

  • Container Image: kodekloud/filebeat-configured

  • Volume Mount: log-volume

  • Mount Path: /var/log/event-simulator/

  • Existing Container Name: app

  • Existing Container Image: kodekloud/event-simulator

     

     

사이드카를 구성해야한다. 

9.

Inspect the Kibana UI. You should now see logs appearing in the Discover section.

 

You might have to wait for a couple of minutes for the logs to populate. You might have to create an index pattern to list the logs. If not sure check this video: https://bit.ly/2EXYdHf

 

 

 

112. Multi-container PODs Design Patterns

There are 3 common patterns, when it comes to designing multi-container PODs. The first and what we just saw with the logging service example is known as a side car pattern. The others are the adapter and the ambassador pattern.

But these fall under the CKAD curriculum and are not required for the CKA exam. So we will be discuss these in more detail in the CKAD course.

 

 

113. InitContainers

In a multi-container pod, each container is expected to run a process that stays alive as long as the POD's lifecycle. For example in the multi-container pod that we talked about earlier that has a web application and logging agent, both the containers are expected to stay alive at all times. The process running in the log agent container is expected to stay alive as long as the web application is running. If any of them fails, the POD restarts.

 

But at times you may want to run a process that runs to completion in a container. For example a process that pulls a code or binary from a repository that will be used by the main web application. That is a task that will be run only  one time when the pod is first created. Or a process that waits  for an external service or database to be up before the actual application starts. That's where initContainers comes in.

초기 실행시 한번에 실행되게 하는 것 

 

An initContainer is configured in a pod like all other containers, except that it is specified inside a initContainers section,  like this:

 

 
apiVersion: v1
kind: Pod
metadata:
  name: myapp-pod
  labels:
    app: myapp
spec:
  containers:
  - name: myapp-container
    image: busybox:1.28
    command: ['sh', '-c', 'echo The app is running! && sleep 3600']
  initContainers:
  - name: init-myservice
    image: busybox
    command: ['sh', '-c', 'git clone <some-repository-that-will-be-used-by-application> ; done;']

When a POD is first created the initContainer is run, and the process in the initContainer must run to a completion before the real container hosting the application starts. 

You can configure multiple such initContainers as well, like how we did for multi-pod containers. In that case each init container is run one at a time in sequential order.

If any of the initContainers fail to complete, Kubernetes restarts the Pod repeatedly until the Init Container succeeds.

 
apiVersion: v1
kind: Pod
metadata:
  name: myapp-pod
  labels:
    app: myapp
spec:
  containers:
  - name: myapp-container
    image: busybox:1.28
    command: ['sh', '-c', 'echo The app is running! && sleep 3600']
  initContainers:
  - name: init-myservice
    image: busybox:1.28
    command: ['sh', '-c', 'until nslookup myservice; do echo waiting for myservice; sleep 2; done;']
  - name: init-mydb
    image: busybox:1.28
    command: ['sh', '-c', 'until nslookup mydb; do echo waiting for mydb; sleep 2; done;']

Read more about initContainers here. And try out the upcoming practice test.

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

 

initContainer 가 실패한다면 될때까지 pod를 재생산한다 .

 

 

114. Practice Test - Init Containers

1.

Identify the pod that has an initContainer configured.

'

init container 섹션을 가지고 있음.

2.

What is the image used by the initContainer on the blue pod?

busybox

3.

What is the state of the initContainer on pod blue?

4.

Why is the initContainer terminated? What is the reason?

 

5.

We just created a new app named purple. How many initContainers does it have?

 

 

6.

What is the state of the POD?

 

7.

How long after the creation of the POD will the application come up and be available to users?

initcontainer 1번이 600 sleep 2번이 1200 30분 

8.

Update the pod red to use an initContainer that uses the busybox image and sleeps for 20 seconds

Delete and re-create the pod if necessary. But make sure no other configurations change.

  • Pod: red

  • initContainer Configured Correctly

     

9.

A new application orange is deployed. There is something wrong with it. Identify and fix the issue.

Once fixed, wait for the application to run before checking solution.

sleep 오타 수정

 

 

116. Self Healing Applications

Kubernetes supports self-healing applications through ReplicaSets and Replication Controllers. The replication controller helps in ensuring that a POD is re-created automatically when the application within the POD crashes. It helps in ensuring enough replicas of the application are running at all times.

Kubernetes provides additional support to check the health of applications running within PODs and take necessary actions through Liveness and Readiness Probes. However these are not required for the CKA exam and as such they are not covered here. These are topics for the Certified Kubernetes Application Developers (CKAD) exam and are covered in the CKAD course.

 

89. Application Lifecycle Management - Section introduction

91. Rolling Updates and Rollbacks

92. Practic Test - Rolling updates and Rollbacks

94. Configure Applications

95. Commands

96. Commands and Arguments

97. Practice Test - Commands and Arguments

99. Configure Environment Variables in Applications 

100. Configuring ConfigMaps in Applications 

101. Practic Test: Environment Variables

103. Kubernetes Secrets

104. A note about Secrets! 

105. Practice Test - Secrets


 

 

 

89. Application Lifecycle Management - Section introduction

 

위와 같이 배워볼 것이다.

 

 

91. Rolling Updates and Rollbacks

 

Rollout and Versioning

deployment 를 만들면 rollout을 만든다. rollout 는 새로운 deployment revision을 만든다. (revision1)

 

새로운 deployment를 만들면 새로운 rollout 과 revision을 만든다. (revision2)

 

revision은 버전 관리에 도움을 준다 .

 

Rollout Command

rollout 을 명령을 하면 pod를 하나씩 교체한다. 

 history 로 확인 가능하다.

 

Deployment Strategy | recreate, Rolling Update

recreate 방식은 모든 인스탄스를 중지하고 새 인스턴스로 한번에 교체하는 것이다.

이때 application이 다운 될 수 있다.

rolling update는 하나씩 교체하는 것이다. 

application이 down 되지 않는다.

rolling update가 기본적인 배포 방식이다.

 

how to update deployment

yaml 파일에서 image 버전을 수정했다고 가정하자
apply 를 하면 변경 사항이 적용된다.

rollout 이 자동 실행된다. 

kubectl set image로 바로 image를 변경할 수 있다. yaml 파일에는 변경되지 않음.

recrate 를 자세히보면 replica를 0으로 줄였다가 5로 다시 늘린다. 

rollingupdate는 하나 줄이고 늘이고 반복하는 식이다.

만약 replica set 1 에서 2 로 업데이트를할때 

replica set2 의 pod 1 생성 set 1의 pod1 종료 

pod2 생성 set1의 pod2 종료 교차식으로 교체한다.

업데이트 완료된 후 확인하면 replicaset1 의 pod는 다 꺼지고 set 2의 pod는 잘 작동중인것을 확인할 수 있다.

 

만약 rollback 하고 싶으면 rollout undo 명령 

rollout 도 마찬가지로 하나씩 교체한다.

명령어 요약! 

 

 

92. Practic Test - Rolling updates and Rollbacks

1.

We have deployed a simple web application. Inspect the PODs and the Services

Wait for the application to fully deploy and view the application using the link called Webapp Portal above your terminal.

사이트 접속

2.

What is the current color of the web application?

Access the Webapp Portal.

blue

 

3.

Run the script named curl-test.sh to send multiple requests to test the web application. Take a note of the output.

Execute the script at /root/curl-test.sh.

/root/curl-test.sh

 

4.

Inspect the deployment and identify the number of PODs deployed by it

5.

What container image is used to deploy the applications?

 

6.

Inspect the deployment and identify the current strategy

7.

If you were to upgrade the application now what would happen?

 

8.

Let us try that. Upgrade the application by setting the image on the deployment to kodekloud/webapp-color:v2

Do not delete and re-create the deployment. Only set the new image name for the existing deployment.

 

CheckCompleteIncomplete

 

simple-webapp=<새로운 이미지 명>

 

9.

Run the script curl-test.sh again. Notice the requests now hit both the old and newer versions. However none of them fail.

Execute the script at /root/curl-test.sh

10.

Up to how many PODs can be down for upgrade at a time

Consider the current strategy settings and number of PODs - 4

25% 가 max 이므로 1개 

11.

Change the deployment strategy to Recreate

Delete and re-create the deployment if necessary. Only update the strategy type for the existing deployment.

 

12.

Upgrade the application by setting the image on the deployment to kodekloud/webapp-color:v3

Do not delete and re-create the deployment. Only set the new image name for the existing deployment.

 

13.

Run the script curl-test.sh again. Notice the failures. Wait for the new application to be ready. Notice that the requests now do not hit both the versions

Execute the script at /root/curl-test.sh.

 

 

 

94. Configure Applications

응용 프로그램 구성은 다음 개념을 이해하는 것으로 구성됩니다.

  • 응용 프로그램에서 명령 및 인수 구성
  • 환경 변수 구성
  • 비밀 구성

우리는 다음에 이것을 볼 것입니다

 

 

95. Commands

우분투 이미지를 가지는 도커 컨테이너를 운영한다고 가정해보자

docker 명령을 실행하면 우분투 인스턴스를 생성한다. 

process status 로 명령하면 아무 컨테이너도 뜨지 않는다.

Exited 상태에 있는 컨테이너를 볼 수 있다.

Containers are not meant to host an operating system.

컨테이너는 가상 컴퓨터와 달리 운영 체제를 호스팅하도록 되어있지 않다.

Containers are meant to run a specific task or process such as to host an instance of a web server or

application server or a database or simply to carry out some kind of computation or analysis once the

task is complete.

컨테이너를 운영체제가 아니다. 여러가지 task를 처리하는 하나의 수단일뿐. 

task를 완료하면 컨테이너는 exit 한다. 

 

컨테이너가 무슨 프로세스를 해야하는지 어떻게 정의를 내릴까?

docker 이미지 파일을 보면 cmd 파트가 있다.

해당 파트를 컨테이너가 할거다? 

mysql 의 이미지 파일
우분투 이미지

우분투 인 경우 cmd 에 ubuntu 가 아니라 bash 라고 쓰여있다.

bash는 터미널의 인풋을 듣는 조형물이다. 

웹서버  데이터베이스 서버 같은 프로세스가 아니다.

 

 

터미널을 찾을 수 없다면 container는 exit 할 거다. 

 

우분투 컨테이너가 생성되고나서 bash 는 터미널을 찾을 수 없기에 exit한다. 

기본값으로 Docker 는 실행 중일 때 컨테이너에 터미널을 연결하지 않는다 .

bash 프로그램은 터미널을 찾지 못해 종료된다.

 

컨테이너 생성시 다르게 옵션을 줘야할 필요가 있다.

 

 

sleep 5 옵션으로 5초동안 살아있다가 exit 한다 .

쉼표 추가

 

매번 시작할때마다 sleep 하도록 설정하는 법

배열의 첫번째 요소는 실행가능해야한다. 

sleeper 를 만들고 적용하기
sleeper 를 지정했다면 바로 10 을 뒤에 파라미터로 사용해도 된다.

Entrypoint 지정함으로서 컨테이너가 실행될 때 우선적으로 실행될 명령어를 지정한다.

 

초에 대한 파라미터를 안주면 에러가 뜬다.

In case of the CMD instruction the command line parameters passed will get replaced entirely, whereas

in case of entry point the command line parameters will get appended.

entrypoint 오버라이드 옵션으로 다른 명령어로 실행되게 할 수 있다.

 

 

96. Commands and Arguments

10초를 sleep 시키고 싶은면 args: ["10] 이렇게 주면 된다.

pod yaml 파일에서 args 에 변수를 입력하면 변수를 사용할 수 있다. 

entrypoint 를 오버라이드 할려면 --entrypoint 옵션을 주면 된다.

yaml 파일에서 command로 entrypoint 오버라이드를 할 수 있다.

 

좀 어렵다. docker 도 따로 공부해야겠다. 

 

 

97. Practice Test - Commands and Arguments

1.

How many PODs exist on the system?In the current(default) namespace

2.

What is the command used to run the pod ubuntu-sleeper?

command

3.

Create a pod with the ubuntu image to run a container to sleep for 5000 seconds. Modify the file ubuntu-sleeper-2.yaml.

Note: Only make the necessary changes. Do not modify the name.

 

4.

Create a pod using the file named ubuntu-sleeper-3.yaml. There is something wrong with it. Try to fix it!

Note: Only make the necessary changes. Do not modify the name.

 

5.

Update pod ubuntu-sleeper-3 to sleep for 2000 seconds.

Note: Only make the necessary changes. Do not modify the name of the pod. Delete and recreate the pod if necessary.

이렇게 바로 edit 이 안된다.

 

vi 에디터로 수정후
apply 하면 인자가 1200, 2000 두개가 뜬다.
이것도 안됨

edit 하고 생긴 파일로 replace 하자!

조금 기다리면 교체된다.

6.

Inspect the file Dockerfile given at /root/webapp-color directory. What command is run at container startup?

pythom, app.py

7.

Inspect the file Dockerfile2 given at /root/webapp-color directory. What command is run at container startup?

ep 가 지정되면 cmd의 내용은 ep의 파라미터가 된다.

8.

Inspect the two files under directory webapp-color-2. What command is run at container startup?

Assume the image was created from the Dockerfile in this directory.

docker 파일과 yaml 파일 같이 정의된 경우 yaml 파일을 따라간다. 

command --color, green 이 실행된다. 

 

9. 

Inspect the two files under directory webapp-color-3. What command is run at container startup?

Assume the image was created from the Dockerfile in this directory.

yaml 파일에 cmd 먼저 실행 arg 적용

 

10.

Create a pod with the given specifications. By default it displays a blue background. Set the given command line arguments to change it to green.

--help 로 확인하기

 

 

99. Configure Environment Variables in Applications 

쿠버네티스에서 환경 변수 설정하는 법!

containers 아래에 env 옵션을 추가한다.

name 은 환경 변수이름 value는 값

아니면 valueFrom 을 이용하여 configMapKeyRef, secretKeyRef 로 숨길 수 있다.

환경 변수를 적용하는 방법 

키 값,

컨피그맵

시크릿키 

100. Configuring ConfigMaps in Applications 

만약 pod 안에 환경 변수를 많이 넣으면 복잡할 거다. 

configMap 을 사용하면 key, value를 중앙에서 관리할 수 있다.

create configMap, Inject into pod 두단계로 나뉜다.

configMap 생성 방법 두가지 

 

create configMap - 명령형

kubectl create configmap

 app-config --from-literal=APP_COLOR=blue

바로 환경 변수를 입력한다. 

The from literal option is

used to specify the key value pairs in the command itself.

from-literal 옵션은 키, 값 바로 있을때

 

kubectl create configmap

 app-config --from-literal=APP_COLOR=blu \
 			--from-literal=APP_MOD=prod

환경변수를 추가하고 싶다면 위와 같이 한다. 

kubectl create configmap

 app-config --from-file=config.properties

파일로 넘겨줄 수 있다.

 

create configMap - 선언형

kubectl create -f config-map.yaml

하고 config-map.yaml 파일을 만든다. 

특이한 점은 spec 대신 data 가 들어간다는 점이다. 

create 까지 해야 configmap 이 구성된다. 

 

 

apiVersion: v1
kind: ConfigMap
metadata:
  name: app-config
data:
  APP_COLOR: blue
  APP_MODE: prod

configmap을 다양한 방식으로 이용할 수 있다. 

kubectl get configmaps

describe 도 가능함. 

Inject into pod

envFrom 을 추가하자.

pod 에 spec -> containers ->

envFrom:

  -configMapRef:

      name: app-config

 

이제 pod 를 실행 시키면 환경변수가 적용될 것이다 .

여러가지 방식으로 환경변수를 가져올 수 있다.

 

101. Practic Test: Environment Variables

1.

How many PODs exist on the system?in the current(default) namespace

2.

What is the environment variable name set on the container in the pod? 

3.

What is the value set on the environment variable APP_COLOR on the container in the pod?

pink

 

4.

View the web application UI by clicking on the Webapp Color Tab above your terminal.

5.

Update the environment variable on the POD to display a green background

Note: Delete and recreate the POD. Only make the necessary changes. Do not modify the name of the Pod.

변경하면 취소된다.

실행중인 pod를 변경한다고 해서 변경되지 않는다. manifest 파일을 수정해야한다. 

대신 수정한 카피에 대한 경로를 준다. 

그때 복제 파일 경로를 얻고 

기존 pod를 delete 하고 

create 한다. 

6.

View the changes to the web application UI by clicking on the Webapp Color Tab above your terminal.

If you already have it open, simply refresh the browser.

 

7.

How many ConfigMaps exists in the default namespace?

 

8.

Identify the database host from the config map db-config

 

 

9.

Create a new ConfigMap for the webapp-color D. Use the spec given below.

  • ConfigName Name: webapp-config-map

  • Data: APP_COLOR=darkblue

10.

Update the environment variable on the POD to use the newly created ConfigMap

Note: Delete and recreate the POD. Only make the necessary changes. Do not modify the name of the Pod.

 

11.

View the changes to the web application UI by clicking on the Webapp Color Tab above your terminal.

 

 

103. Kubernetes Secrets

비밀 번호 같이 사적인 데이터를 위처럼 표기한다면 위험하다. 

그래서 Secret 이 필요하다.

 

마찬가지로 create secret, inject into pod 두가지 단계가 필요함

명령형 , 선언형 생성가능하다.

명령형

kubectl create secret generic  

이렇게 생성한다.

선언형

키 ,값을 yaml 파일에 바로 집어넣으면 안되고 암호화된 값을 넣어야한다. 어떻게 변환 하는가 ?

위와 같은 명령어로 암호화 할 수 있다.

describe 로 보면 안에 데이터를 볼 수 는 없다. 

확인하고 싶다면 yaml 파일을 확인

-o yaml 옵션 사용

 

 

어떻게 복호화 할까 

decode 옵션을 사용하면 된다. 

secretRef inject 하기

envFrom 후에 

secretRef 로 추가한다.

 

위와 같은 방식으로 inject 하기

ls를 이용하면 secret 속성을 확인가능. 세개의 파일이 있음.

Secret은 완전히 암호화된 것이 아니다. 

그냥 인코딩 된것 

누구나 인코딩된 내용을 볼 수 있다. 

ETCD 에 암호화되지 않는다. 

github 이런데 올리지 마라 

클라우드 사업자이 제공하는 secret store 를 고려해보자! 

 

 

104. A note about Secrets! 

Remember that secrets encode data in base64 format. Anyone with the base64 encoded secret can easily decode it. As such the secrets can be considered as not very safe.

The concept of safety of the Secrets is a bit confusing in Kubernetes. The kubernetes documentation page and a lot of blogs out there refer to secrets as a "safer option" to store sensitive data. They are safer than storing in plain text as they reduce the risk of accidentally exposing passwords and other sensitive data. In my opinion it's not the secret itself that is safe, it is the practices around it. 

Secrets are not encrypted, so it is not safer in that sense. However, some best practices around using secrets make it safer. As in best practices like:

  • Not checking-in secret object definition files to source code repositories.
  • Enabling Encryption at Rest for Secrets so they are stored encrypted in ETCD. 

 

Also the way kubernetes handles secrets. Such as:

  • A secret is only sent to a node if a pod on that node requires it.
  • Kubelet stores the secret into a tmpfs so that the secret is not written to disk storage.
  • Once the Pod that depends on the secret is deleted, kubelet will delete its local copy of the secret data as well.

Read about the protections and risks of using secrets here

Secrets | Kubernetes

Having said that, there are other better ways of handling sensitive data like passwords in Kubernetes, such as using tools like Helm Secrets, HashiCorp Vault. I hope to make a lecture on these in the future.

 

 

105. Practice Test - Secrets

1.

How many Secrets exist on the system?

2.

How many secrets are defined in the dashboard-token secret?

3

 

3.

What is the type of the dashboard-token secret?

 kubernetes.io/service-account-token

 

4.

Which of the following is not a secret data defined in dashboard-token secret?

 

 

5.

We are going to deploy an application with the below architecture. We have already deployed the required pods and services. Check out the pods and services created. Check out the web application using the Webapp MySQL link above your terminal, next to the Quiz Portal Link.

 

 

6.

The reason the application is failed is because we have not created the secrets yet. Create a new secret named db-secret with the data given below. You may follow any one of the methods discussed in lecture to create the secret.

  • Secret Name: db-secret

  • Secret 1: DB_Host=sql01

  • Secret 2: DB_User=root

  • Secret 3: DB_Password=password123

 

7.

Configure webapp-pod to load environment variables from the newly created secret.

Delete and recreate the pod if required.

  • Pod name: webapp-pod

  • Image name: kodekloud/simple-webapp-mysql

  • Env From: Secret=db-secret

 

8.

View the web application to verify it can successfully connect to the database

 

 

81. Logging and Monitoring Section Introduction

83. Monitor Cluster Components

84. Practice Test - Monitoring 

86. Managing Application Logs

87. Practice Test - Monitor Application Logs

 

 

 

81. Logging and Monitoring Section Introduction

We first see how to monitor the kubernetes cluster components as well as the applications hosted

on them. We then see how to view and manage the logs for the cluster components as well as the applications.

모니터링과 관리를 배워볼 것이다. 

 

 

 

83. Monitor Cluster Components

자원소비를 어떻게 모니터링 할까 ? 

무엇을 모니터링 해야할까? 

 

상황을 분석하고 저장하는 데이터 베이스가 필요하다. 

 

쿠버네티스에서 자체 모니터링 서비스를 가지지는 않다.

 

Metrics server, prometheus, elastic stack, data dog , dynatrace 등  모니터링 오픈 소스가 있다. 

 

heapster 가 있었는는데 이제 metric server로 개명되었다. 

 

한 쿠버 클러스터당 하나의 metrics server를 가질 수 있다. 

 

Note that the metric server is only an in memory monitoring solution and does not store the metrics

on the desk and as a result you cannot see historical performance data.

metrics server 만 유일하게 memory 에 저장한다. 그런데 desk 에 저장하지 않는다 ?  뭐지...

 

kublet 안에 container advisor, cAdvisor 가 있다. 

kublet 이 pod로부터 퍼포먼스 정보를 받고 kube api를 경유하여 metrics server 로 정보를 보낸다. 

 

minikube addons enable metrics-server

위 명령을 통해서 metrics server 를 이용할 수 있다.

 

kubectl top node

명령을 쓰면 cpu, memory 사용량을 볼 수 있다.

 

kubectl top pob

파드의 성능 지표를 확인할 수 있다. 

 

84. Practice Test - Monitoring 

1.

We have deployed a few PODs running workloads. Inspect them.

Wait for the pods to be ready before proceeding to the next question.

2.

Let us deploy metrics-server to monitor the PODs and Nodes. Pull the git repository for the deployment files.

 

3.

Deploy the metrics-server by creating all the components downloaded.

Run the kubectl create -f . command from within the downloaded repository.

방금 설치한 metrics server 폴더로 이동한 후 create -f .

4.

It takes a few minutes for the metrics server to start gathering data. 

Run the kubectl top node command and wait for a valid output.

5.

Identify the node that consumes the most CPU.

 

6.

Identify the node that consumes the most Memory.

마찬가지

 

7.

Identify the POD that consumes the most Memory.

8.

Identify the POD that consumes the least CPU.

lion

 

 

 

86. Managing Application Logs

 

로깅 메카니즘을 배워보자

event-simulator 를 사용하면 docker 가 랜덤으로 이벤트를 만든다.

-d detach 모드로 하면 안보인다. docker logs -f 컨테이너이름 을 통해서 볼 수 있다.

쿠버네티스에서  pod를 생성하고

마찬가지로 log -f 명령을 통해서 로그를 볼 수 있다. 

pod는 여러개의 컨테이너를 담을 수 있다. 만약 컨테이너를 하나 더 추가하고 log를 하면 어떤 container log를 보여줄까? 

그냥하면 아무것도 안뜨고 pod 네임 container 네임 다 명시해야 log가 뜬다. (event-simulator) 

 

 

 

 

87. Practice Test - Monitor Application Logs

1.

We have deployed a POD hosting an application. Inspect it. Wait for it to start.

2.

A user - USER5 - has expressed concerns accessing the application. Identify the cause of the issue.

Inspect the logs of the POD

 

3.

We have deployed a new POD - webapp-2 - hosting an application. Inspect it. Wait for it to start.

 

4.

A user is reporting issues while trying to purchase an item. Identify the user and the cause of the issue.

70. Daemon Sets

 

daemon sets 에 대해 배워보자
여러 worker node 를 걸쳐 deployment , replicaSet, daemon Sets 이 존재한다.

Daemon Set 은 모든 node에 기본적으로 하나의 pod를 올리게 한다.

 

node가 하나 추가되면 daemon sets의 pod 이 생성되고

그 node가 사라지면 자동적으로 pod도 사라진다. 

 

Daemon Set은 모든 node 에 한 pod가 생기도록 보장한다. 

 

Daemon Sets 사용사례

모든 node 에 모니터링 솔루션이 존재하도록 할 수 있다.

다른 pod 끼리 통신하는 kube proxy 도 예로 들 수 있다.

weave - net 도 가능

kind 는 DaemonSet

replicaset 이랑 비슷한 형태이다.

selector의 레이블과 app의 레이블이 같은지 확인해야한다. 

 

확인하기 

어떤 식으로 작동할까? 

마찬가지로 모든 pod에 node affinity 가 적용되서 node 에 pod이 실리는 방식

 

 

71. Practice Test - DaemonSets

 

1.

How many DaemonSets are created in the cluster in all namespaces? Check all namespaces

 

2.

which namespaces are the DaemonSets created in? 

 

3.

Which of the below is a DaemonSet?

 

4.

On how many nodes are the pods scheduled by the DaemonSet kube-proxy

 

5.

What is the image used by the POD deployed by the kube-flannel-ds DaemonSet?

 

6.

Deploy a DaemonSet for FluentD Logging. Use the given specifications.

먼저 deployment로 생성

kind를 daemonset으로 변경 

replica , strategy, status 제거

 

73. Static Pods

kublet 이 어떻게 작동하는지 알아볼거다

The kublet relies on the kube-apiserver for instructions on what PODs to load on its node,

kublet 은 kube apiserver에 의존한다. 어떤 pod를 node 에 실을지.

 

해당 사항은 etcd 에 저장된 정보를 가지고 kube-scheduler 가 결정한다.

 

만약 master node가 없는 상황이라면 어떨까?

cluster 없이 worker node 하나만 있는 상황에서 kublet은 뭘 할 수 있을까?kublet 단독으로 node를 운영할 수 있을까? 그렇다면 어떤식으로 운영할까?

 

The one thing that the kubelet knows to do is create PODs. But we don’t have an API server here to provide

POD details.

master node, kube api 가 없는 상황에서 kublet이 pod를 만들고 싶어도 pod 정보를 api로 못 받기 때문에 만들 수 없다.

pod 에 대한 정보를 갖고 있는 pod.yaml을 node 안에 미리 저장하고 

kublet 이 우선적으로 해당 파일을 읽도록 지정해야한다.

 

pod를 생성하는것 뿐만 아니라 pod가 살아있도록 유지해야한다.

 

만약 yaml 파일을 변경한다면 kublet은 다시 pod를 생성할 것이다 .

파일을 삭제한다면 pod도 삭제될 것이다. 

 

이렇게 생성된 pod는 kube api 없이 스스로 생성된 것이다. 

 

위처럼 api 도움 없이 kublet 이 생성한 pod를 static pod 라고 한다. 

 

Remember you can only create PODs this way.

You cannot create replicasets or deployments or services by placing a definition file in the designated

directory.

이런 방식으로 생성할 수 있는건 pod 밖에 없다. deployment, service 이런건 안된다.

 

kublet은 pod 레벨에서만 작동하고 이해한다.

그래서 static pod를 생성할 수 있는 것이다. 

 

yaml 파일 경로를 직접 정할 수 있다.

pod-manifest-path=/etc/kubernetes/manifests

기본적으로 위의 경로를 쓴다.

경로를 직접 지정하는 대신 경로 정보를 가지는 config 를 통해서 간접 지정할 수 있다.

kubeconfig yaml 에 경로가 있다.

static pod 가 생성되고 난 후 docker ps 명령어로 확인할 수 있다.

 

kube api 가 없기 때문에 kubectl은 실행되지 않는다. 

master node 가 있는 상황에서 어떻게 작동할까? 

kublet은 static pod 와 api로부터 받은 pod 다 생성할 수 있다. 

 

kube api는 static pod 가 생성되었다는 것을 알까?

확인가능하다.

When the kubelet creates a static pod,

if it is part of a cluster, it also creates a mirror object in the kubeapi server.

What you see from the kube-apiserver is just a read only mirror of the pod. 

cluster 가 있는 상태에서 static pod 가 생성되면 미러 object 가 kubeapi server 에 생성된다. 

get pods 로 확인한건 미러 object 이다 .

만약 static pod를 지우고 싶으면 기존의 방법으로는 지울 수 없다. 

yaml 파일로 가서 수정해야한다. 

static pods 의 용도는 ? 

 you can use static pods to deploy the control plane components itself as pods on a node. Start by installing kubelet on all the master nodes.

마스터 node에 심어놓을 수 있다.

만약 pod 가 죽었을때 master node 에 pod 에 대한 정의가 있으면 다시 만들 수 있다. (매번 번거롭게 외부 접속 안해도 된다.) 

static pod 와 daemonset의 차이! 

 

74. Practice Test - Static Pods

 

1.

How many static pods exist in this cluster in all namespaces?

먼저 확인한다.

이름 뒤에 노드 있는 애들을 static pod 로 간주한다. 

pod의 yaml 파일을 열어서 확인해보자
ownerReferences 의 kind에 node 라고 되어있다

 

static pod 가 아니면 다른 kind 로 되어있다.

 

 

2.

Which of the below components is NOT deployed as a static pod?

3.

Which of the below components is NOT deployed as a static POD?

 

4.

On which nodes are the static pods created currently?

 

 

5.

What is the path of the directory holding the static pod definition files?

6. 

How many pod definition files are present in the manifests folder?

 

 

7.

What is the docker image used to deploy the kube-api server as a static pod?

 

8.

Create a static pod named static-busybox that uses the busybox image and the command sleep 1000

파일을 만든다. command는 뒤에 온다.
파일을 static pod 경로에 복사

9.

Edit the image on the static pod to use busybox:1.28.4

vi 에디터로 편집

10.

We just created a new static pod named static-greenbox. Find it and delete it.

This question is a bit tricky. But if you use the knowledge you gained in the previous questions in this lab, you should be able to find the answer to it.

manifests 경로에 없다.
다른 node 에 생성된 static pod 일 것이다 .
해당 ip 로 접속
위 경로에도 없다.
파일을 삭제

 

exit 하고 확인하면 됨 

 

 

76. Multiple Schedulers

 

 

kube 은 scheduler를 각기 다르게 정의할 수 있다. 

 

가장 기본이 되는 shceduler는 default scheduler 

추가 scheduler 운영하기

config 파일에서 scheduler 이름을 지정해야하고 yaml 파일에 똑같은 이름을 써야한다.

 

yaml 파일 

leaderElect 옵션이 있다. 

해당 scheduler를 메인으로 쓸거면 true 아니면 false

scheduler를 만들고 난 후 (my-custom-scheduler

 

pod에 schedulerName을 지정해야한다. 

지정하고 나면 pod가 실행될 거다 .

커스텀 scheuler가 파드를 옮겼는지 확인하는 방법은 ?

 

event로 schedule 활동을 볼 수 있다.  -o wide 옵션으로 확인하자 

로그 확인하기 

logs 명령어로 확인도 가능하다.

 

77. Practice Test - Multiple Schedulers

1.

 

What is the name of the POD that deploys the default kubernetes scheduler in this environment?

2. 

What is the image used to deploy the kubernetes scheduler?

Inspect the kubernetes scheduler pod and identify the image

3.

We have already created the ServiceAccount and ClusterRoleBinding that our custom scheduler will make use of.

 

Checkout the following Kubernetes objects:

ServiceAccount: my-scheduler (kube-system namespace)
ClusterRoleBinding: my-scheduler-as-kube-scheduler
ClusterRoleBinding: my-scheduler-as-volume-scheduler

Run the command: kubectl get serviceaccount -n kube-system & kubectl get clusterrolebinding

Note: - Don't worry if you are not familiar with these resources. We will cover it later on.

 

4.

Let's create a configmap that the new scheduler will employ using the concept of ConfigMap as a volume.
We have already given a configMap definition file called my-scheduler-configmap.yaml at /root/ path that will create a configmap with name my-scheduler-config using the content of file /root/my-scheduler-config.yaml.

 

기존의 config 파일을 이용하여 configamp 만들기

기존 파일
configmap 도 객체

--from-file 로 가져오는 것

 

5.

Deploy an additional scheduler to the cluster following the given specification.

Use the manifest file provided at /root/my-scheduler.yaml. Use the same image as used by the default kubernetes scheduler.

  • Name: my-scheduler

  • Status: Running

  • Correct image used?

     

     

     

     

default scheduler 에서 사용하는 image 확인
yaml 파일에 image 복붙
강제 시작

 

6.

A POD definition file is given. Use it to create a POD with the new custom scheduler.

File is located at /root/nginx-pod.yaml

방금 만든 scheduler 를 쓰자
schedulerName 추가
강제 실행

 

79. Configuring Scheduler Profiles 

배정 받기를 기다리는 pod 와 node 가 있다.

위와 같이 사양이 있다고 치자.

1. Scheduling Queue

여러 pod 들이 scheduling 되기 기다리는데 이것을 queue 라고 한다.

 

value 1만으로 지정했다. 높을 수록 먼저!

파드에 priorityClassName 을 쓰기 위해  PrirorityClass 객체를 만들어야한다. 

 

value 가 큰 값 먼저 배치한다. 

파드가 대기자 큐에 올라간다. 

 

 

2. Filtering

사양에 맞는 node를 필터링한다. 

 

3. Scoring

node 할당 후 자원이 많이 남는 node를 고른다 .

 

4. Binding

\

pod가 node 에 배정된다 .

 

Scheduling Plugins

모든 과정에 plugins 이 관여한다 .

 

pod 우선 순위
node 자원 확인, nodeName 이름 여부, NodeUnschedulable 옵션

 

unschedulable 옵션
node 점수매기기, imageLocality ?
binding 에 관여

Extension Points

 

여러 지점이 존재한다.

 

plugins 들을 수정할 수 있다. 

scheduler profiles 를 계속 추가한다.

어떻게 scheduler를다르게 설정할 수 있을까 ?

Extension을 다르게 설정함으로서 다양한 scheduler 를 만들 수 있다.

 

 

80. References

References

https://youtu.be/fbGyQMOSqbE

1. 쿠버네티스 기반 PaaS를 통한 클라우드 혁신과 적용사례

 

IaaS : 인프라 자원을 제공하는 것이 목적

Paas : 인프라 자원 위에 애플리케이션을 개발하고 실행하는 것이 목적 

paas 는 자동화된 영역이 많으니 운영이 빠르다.

컨테이너 방식은 운영 관리가 쉽다.

커널은 공유된다. 

 

컨테이너 장점
컨테이너 오케스트레이션 쿱
infra node를 worker node로 구성해도된다.
쿠버네티스 활용 사례 3가지

devops, 멀티 클라우드, msa

 

DevOps로 활용

 

 

아키텍처 위처럼 짜도될듯?

 

CI /CD pipeline 만들기
콜센터 사례
레거시 환경대비 향상이 있을 수도 있다.

 

하이브리드 클라우드

하이브리드 클라우드
재해복구 센터
개발은 private, 서비스 배포는 public
private 서버에서 과부하시 public 클라우드로 scale out

private cloud 에서 분석을 다 해놨다가 연산 과정에서 public cloud를 사용

비용 절감. 

 

MSA

개발, 배포, 확장이 중요해졌음.
미니 서비스들이 모여있음.
느슨한 결합 구조를 가져야한다.
데이터 중복, 정합성 지키기가 어렵다 .
api gateway 으로 통신한다는 점. 호출 , 통신을 잘 매칭해줘야함.

 

 


2. [Kubernetes Service] 클라우드 시장의 대세, 쿠버네티스란 무엇인가?

https://youtu.be/JNc11rxLtmE

이거 나중에 정리 해보자 

직접적인 사례보다 어떤식으로 운영하는지에 대한 정보. 쿠버네티스의 장점을 설명하는 영상

나중에 정리하겠습니다.


 

 

3. 쿠버네티스 : 마이크로서비스 아키텍처에 대한 구축 사례와 데모를 통한 확실한 개념 잡기

https://youtu.be/GOZ6GM287Fc

쿠팡

부분 장애가 전체 서비스 장애로 이어짐? 

빨간 상자 하나 하나다 마이크로서비스이다.
msa 도입의 장단점

데모 MSA 구성

예제

시나리오 1- 별점 서비스 장애 데모

리뷰에 오류가 발생한다면 ?

 

오류 테스트 하기 위해 review pod를 꺼버렸다.

 

새로고침을 하면 review 파트만 빼고 나머지는 정상적으로 돌아간다. 

KIALI
Jaeger

마이크로서비스 트래픽 관리

시나리오 2 - 일부 사용자만 특정 버전으로 유입

 

사용자에 따라 접근을 다르게 할 수 있다 -> 트래픽 관리 가능

시나리오 3 - 카나리 배포 일부 사용자만 특정 버저너으로 유입

카나리 배포 - 점진적 배포
weight 로 비율조절
기존
weight를 주고 비율이 달라짐.

 

+ Recent posts