Skip to main content

· 3 min read

DNS 서버에 보내는 방법

cat /etc/resolv.conf

nameserver 192.168.1.100

모르는 이름의 호스트를 마주치면 DNS 서버에서 이름을 가져오게 됨.

ip link 

ip addr

ip addr add 192.168.1.10/24 dev eth0

ip route

ip route add 192.168.1.10/24 via 192.168.2.1

arp

netstat -plnt
  1. Create Network namespace
  2. Create Bridge Network/Interface
  3. Create vETH Pairs
  4. Attach vETH to Namespace
  5. Attach Other vETH to Bridge
  6. Assign IP Address
  7. Bring the Interface Up
  8. Enable NAT -IP Masquerade

이 모든 일련의 과정을 create Network Namespace 로 통합하였다.

bridge add <cid> <namespace>

CNI (Container Network Interface)​

컨테이너 런타임 환경에서 네트워킹 문제를 해결하기 위해 어떻게 개발되어야할지 정의하는 표준의 집합

실습​

What is the network interface configured for cluster connectivity on the controlplane node?

node-to-node communication

then

What is the MAC address assigned to node01?

kubectl get nodes -o wide
> {ip 주소}

ip a | grep {ip 주소}
> 6254: eth0@if6255: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1450 qdisc noqueue state UP group default
link/ether 02:42:c0:16:ad:09 brd ff:ff:ff:ff:ff:ff link-netnsid 0 # Mac 주소
inet 192.22.173.9/24 brd 192.22.173.255 scope global eth0 #

ssh node01
같은 것 반복

Pod Networking​

net.script.sh

AS-IS 
# create Veth Pair
ip link add

# Attach Veth Pair
ip link set ...
ip link set ...

# Assign IP Address
# Invoke IPAM host-local plugin
ip = get_free_ip_from_file() => /etc/cni/net.d/net-script.conf (아웃소싱 개념)
ip -n <namespace> addr add ..
ip -n <namespace> router add ..

# Bring it up Interface
ip -n <namespace> link set

겁나게 복잡한 일련의 과정을 CNI를 통해 다음의 한줄로 요약이 가능하다.

/etc/cni/net.d/net-script.conflist → /opt/cni/bin/net-script.sh → ./net-script.sh add <container> <namespace

TO-BE
ip -n <namespace> link set ...

ip link del ...

CNI in kubernetes​

kubelet.service 
ps -aux | grep kubelet

--network-policy=cni
--cni-bin-dir=/opt/cni/bin
--cni-conf-dir=/etc/cni/net.d

실습​

What is the POD IP address range configured by weave? ip addr show weave

kubectl logs -n kube-system weave-net-xx | grep ipalloc-range

Service Networking​

가상의 IP가 만들어지고 각 node에 ip를 배치하게 된다.

ClusterIP라고도 부른다.

iptables -L -t nat | grep db-service

cat /var/log/kube-proxy.log 에서

DNS in kubernetes Cluster​

Alt text

HostnameNamespaceTypeRootIP Address
web-serviceappssvccluster.local10.107.37.188
10-244-2-5appspodcluster.local10.244.2.5

curl web-service.apps.svc.cluster.local curl 10-244-2-5.apps.pod.cluster.local

· 11 min read

Authenticate​

kubernetes 인증 어떻게 이루어질까?

User → Kube-apiserver → Process 인데 Kube-apiserve에서 인증을 먼저 시도한다.

인증의 방식 4가지

  1. static password file

    --basic-auth-file=user-details.csv
  2. static token file

    --token-auth-file=user-details.csv
    • kube-apiserver.service를 살펴보면 다음의 옵션을 추가해주면 된다.

    • /etc/kubernetes/manifests/kube-apiserver.yaml 에 옵션을 추가할 수 있다.

    • 수정이 일어나게 되면 알아서 kube-apiserver가 재구동 된다.

    • 다음의 요청으로 api-server를 요청할 수 있다.

      curl -v -k https://~~~pods --header="Authorization : Bearer iuhsliugidfu" 
  3. certificate

  4. identity service

TLS​

비대칭 암호화 방식을 흔히 퍼블릭키와 프라이빗 키라고 얘기하는데 사실은 퍼블릭 잠금이 있을 뿐이다. Alt text

Public Lock = Publick Key 하는일: 암호화 *.crt, *pem server.crt, server.pem

Private Key 하는일 복호화 *.key, *-key.pem server.key, server-key.pem

# 내 환경에서 로그인 하기
ssh-keygen
# id_rsa(private key) id_rsa.pub(public Lock)

cat ~/.ssh/authorized_keys
# ssh-rsa AAdufhius user1

ssh -i id_rsa user1@server1

# 다른 사용자가 내 환경에서 로그인 하기
cat ~/.ssh/authorized_keys

TLS in K8s​

Client Certificates for Clients​

Generate Keys - openssl genrsa -out ca.key 2048

Certificate Signing Request openssl req -new -key ca.key -subj "/CN=KUBERNETES-CA" -out ca.csr

Sign Certificates openssl x509 -req -in ca.csr -signkey ca.key -out ca.crt

Admin User

Generate Keys - openssl genrsa -out admin.key 2048

Certificate Signing Request openssl req -new -key admin.key -subj "/CN=kube-admin" -out admin.csr

Sign Certificates openssl x509 -req -in admin.csr -CA ca.crt -CAKey ca.key -out admin.crt

Kube Scheduler

Kube Proxy …

curl https://kube-apiserver:6443/api/v1/pods --key admin.key --cert admin.crt --cacert ca.crt

혹은
Kubeconfig 파일을 만든다.

Server Certificates for Servers​

Untitled

클러스터 내의 모든 인증서 어떻게 설정됐는지 알아보자

실습​

Identify the Certificate file used to authenticate kube-apiserver as a client to ETCD Server.

 --etcd-keyfile=/etc/kubernetes/pki/apiserver-etcd-client.crt

Identify the key used to authenticate kubeapi-server to the kubelet server.

--kubelet-client-key=/etc/kubernetes/pki/apiserver-kubelet-client.key

Identify the ETCD Server Certificate used to host ETCD server.

--cert-file=/etc/kubernetes/pki/etcd/server.crt

Identify the ETCD Server CA Root Certificate used to serve ETCD Server.

ETCD can have its own CA. So this may be a different CA certificate than the one used by kube-api server.

--trusted-ca-file=/etc/kubernetes/pki/etcd/ca.crt

What is the Common Name (CN) configured on the Kube API Server Certificate?

OpenSSL Syntax: openssl x509 -in file-path.crt -text -noout

How long, from the issued date, is the Root CA Certificate valid for?

File: /etc/kubernetes/pki/ca.crt

openssl x509 -in /etc/kubernetes/pki/ca.crt -text -noout

Certificate API​

  1. Create CertificateSigningRequest Object
  2. Review Request
  3. Approve Request
  4. Share Certs to User

kubectl get csr

kubectl certificate approve jane

cat akshay.csr | base64 -w 0
<base64 csr content>
---
apiVersion: certificates.k8s.io/v1
kind: CertificateSigningRequest
metadata:
name: akshay
spec:
groups:
- system:authenticated
request: <Paste the base64 encoded value of the CSR file>
signerName: kubernetes.io/kube-apiserver-client
usages:
- client auth

ontroller Manager에서 인증을 담당하고 있다.

더 자세하게 들어가면

CSR-Approving

CSR Signing

kube-controller-manager.yaml

--cluster-signing-cert-file=/etc/kubernetes/pki/ca.crt
--cluster-signing-key-file=/etc/kubernetes/pki/ca.key

What is the Condition of the newly created Certificate Signing Request object?

kubectl get csr

Approve the CSR Request

kubectl certificate approve akshay

deny the agnet-smith

kubectl certificate deny agent-smith

KubeConfig​

KubeConfig는 3가지로 이루어져있다.

Kubeconfig는 3개로 이루어져 있다.

  1. Clusters
  2. Contexts
  3. Users

우린 그동안 인증을 뒤에 붙여놓고 kube-apiserver에 명령을 내릴 수 있었다.

kubectl get pods --server my-kube-cluster:443\
--client-key admin.key
--client-certificate admin.crt
--certificate-authority ca.crt

하지만 kubeconfig를 사용하면 뒤에 덕지덕지 붙은 옵션값들을 안 넣을 수 있다.

$Home/.kube/config 에있는 KubeConfig 파일을 읽는다.

kubeconfig로 다른 환경에 들어가고 싶을 때

kubectl config view
kubectl config use-context prod-user@production
kubectl config use-context context-name --kubeconfig /root/my-kube-config

API Groups​

kube api server와 다름 /api /apis에 포커싱을 한다.

/version : 쿠버네티스 버전을 살피기 위함

/metrics /healthz 상태를 모니터링 하기 위함

/log 로깅을 위함

/api : core group

/apis : API Group

/apps

/v1 : Resources

/deployment

list get create delete

/replicasets

/statefulsets

/networking.k8s.io

/v1 : Resources

/networkpolicies

/authentication.k8s.io

/storage.k8s.io

/certificates.k8s.io

/v1 : Resources

/certificatesigningrequests

curl http://localhost:6443 -k

curl http://localhost:6443/apis -k | grep "name"

Authorization - 허가​

create role

# kubectl get roles
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: developer
rules: #(룰은 3가지로 이루어져있음)
- apiGroups: [""]
resources: ["pods"]
verbs: ["list", "get", "create", "update", "delete"]
- apiGroups: [""]
resources: ["ConfigMap"]
verbs: ["create"]

Role binding

# kubectl get rolebindings
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: devuser-developer-binding
subjects:
- kind: User
name: dev-user
apiGroup: rbac.authorization.k8s.io
roleRef:
kind: Role
name: developer
apiGroup: rbac.authorization.k8s.io

Check Access​

kubectl auth can-i create deployments --as devuser --namespace test
kubectl auth can-i delete nodes

권한을 이용해서 실행하기​

dev-user 에게 네임스페이스 blue 에서 create deployment 권한이 있고, create deployment를 실행해라

kubectl --as dev-user create deployment nginx

Cluster Role and Role Binding​

Cluster Admin에서 View Node delete Node delete Node 의 권한을 줄 수 있다.

get | watch | list  create | delete

Service Account​

계정엔 두개가 존재한다. User Account와 Service Account. 이전 내용들은 모두 user account에 관한 내용이었다. 하지만 이제부턴 시스템이 사용하는 service account를 다뤄볼 것이다. 대표적으로 prometheus, jenkins가 사용하는 계정이 있다.

만약 kube-apiserver를 통해 쿠버네티스 안의 pod등의 정보를 가져오는 service account 예시 또한 들 수 있다.

# pod-definition.yaml
apiVersion: v1
kind: Pod
metadata:
name:
spec:
containers:
- name: my-kubernetes-dashboard
image: my-kubernetes-dashboard
**serviceAccountName: dashboard-sa**
  1. service account 계정 생성
  2. Secret에 token 저장 해당 토큰은 https rest call 할 때, —header Bearer token {token} 으로 인증된다.

네임스페이스는 default가 기본이고 namespace 별로 다르게 생성할 수 잇다.

kubectl exec -it my-kubernetes-dashboard --ls /var/run/secrets/kubernetes.io/serviceaccount

service account의 권한은 kube-apiserver에 쿼리하는 정도의 제한된 권한만 가지고 있음.

실습 문제​

The application needs a ServiceAccount with the Right permissions to be created to authenticate to Kubernetes. The default ServiceAccount has limited access. Create a new ServiceAccount named dashboard-sa.

# SA service account 위한 토큰 만들기
kubectl create token dashboadr-sa

You shouldn't have to copy and paste the token each time. The Dashboard application is programmed to read token from the secret mount location. However currently, the default service account is mounted. Update the deployment to use the newly created ServiceAccount

Edit the deployment to change ServiceAccount from default to dashboard-sa.

서비스 토큰을 마운트 시키기

apiVersion: deployment
kind: Deployment
metadata: ...
spec:
serviceAccountName: dashboard-sa
containers: ...

Image Security​

docker login private-registry.io

docker run private-registry.io/apps/internal-app

kubectl create secret docker-registry regcred \
--docker-server=private-registry.io \
--docker-username=registry-user \
--docker-password=regisry-password \
--docker-email=registry-user@org.com
# pod-definition.yaml
apiVersion: v1
kind: Pod
metadata:
name:
spec:
containers:
- name: nginx
image: private-registry.io/apps/internal-app
imagePullSecrets:
- name: regcred

실습문제​

Create a secret object with the credentials required to access the registry.

Name: private-reg-cred

Username: dock_user

Password: dock_password

Server: myprivateregistry.com:5000

Email: dock_user@myprivateregistry.com

kubectl create secret docker-registry private-reg-cred --docker-server=myprivateregistry.com:5000 --docker-username=dock_user --docker-password=dock_password --docker-email=dock_user@myprivateregistry.com

kubectl create secret docker-registry private-reg-cred --docker-username=dock_user --docker-password=dock_password --docker-server=myprivateregistry.com:5000 --docker-email=dock_user@myprivateregistry.com

Docker Security​

컨테이너와 호스트가 같은 커널을 사용한다. 컨테이너는 리눅스에서 namespace에 의해 격리된다.

host와 container는 namespace가 존재한다. 결국 다른 PID로 격리되도록 한다.

만약 특정 컨테이너의 user가 root 사용자가 아니길 원한다면..?

docker run --user=1000 ubuntu sleep 1000

# pod 레벨에서 보안
apiVersion: v1
kind: Pod

spec:
securityContext:
runAsUser: 1000 # 1000번 사용자로 실행해라
containers:
image:
--------------
# container 레벨에서 보안
apiVersion: v1
kind: Pod

spec:
securityContext:
runAsUser: 1000 # 1000번 사용자로 실행해라
containers:
- image:
securityContext:
runAsUser: 1000 # 1000번 사용자로 실행해라
capabilities:
add: ["MAC_ADMIN"]

Network Policy​

Ingress(인입을 받는)와 Egress(밖으로 호출하는) 개념이 있다.

수행 :Allow Ingress Traffic From API Pod on port 3306

# MYSQL DB Ingress (웹 Backend로 부터 인입을 받아야하는)
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name:
spec:
podSelector:
matchLabels:
role: db
policyTypes:
- Ingress
ingress:
- from:
- podSelector:
matchLabels:
name: api-pod
ports:
- protocol: TCP
port: 3306

prod namespace내에서 잘 통신하고 있었는데, 만약 다른 namespace의 api-pod들이 접근하려고 하는데 이를 막으려면?​

# MYSQL DB Ingress (웹 Backend로 부터 인입을 받아야하는)
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name:
spec:
podSelector:
matchLabels:
role: db
policyTypes:
- Ingress
ingress:
- from:
# 특정 pod에게만 접근을 허용 # && 특정 Namespace에게만 접근을 허용
- podSelector:
matchLabels:
name: api-pod
namespaceSelector:
matchLabels:
name: prod
- ipBlock:
cidr: 192.168.5.10/32
ports:
- protocol: TCP
port: 3306

api-pod &amp;&amp; prod

depth (-)를 다르게 하여 조건을 변경할 수 있다.​

# MYSQL DB Ingress (웹 Backend로 부터 인입을 받아야하는)
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name:
spec:
podSelector:
matchLabels:
role: db
policyTypes:
- Ingress
ingress:
- from:
# 특정 pod에게만 접근을 허용 || 특정 Namespace에게만 접근을 허용
- podSelector:
matchLabels:
name: api-pod
- namespaceSelector:
matchLabels:
name: prod
- ipBlock:
cidr: 192.168.5.10/32
ports:
- protocol: TCP
port: 3306

api-pod || prod

# MYSQL DB Ingress (웹 Backend로 부터 인입을 받아야하는)
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name:
spec:
podSelector:
matchLabels:
role: db
policyTypes:
- Ingress
- Egress
ingress:
- from:
# 특정 pod에게만 접근을 허용 || 특정 Namespace에게만 접근을 허용
- podSelector:
matchLabels:
name: api-pod
ports:
- protocol: TCP
port: 3306
egress:
- to:
- ipBlock:
cidr: 192.168.5.10/32
ports:
- protocol: TCP
port: 80

from api-pod to backend server

· 3 min read

# Create a new pod with the nginx image.
kubectl run nginx --image=nginx

# Create a new pod with the name redis and the image redis123.
kubectl run redis --image=redis123 --dry-run=client -o yaml

kubectl create -f redis.yaml

# Now change the image on this pod to redis.
# Once done, the pod should be in a running state.
kubectl edit pod redis

# If you used a pod definition file then update the image from redis123 to redis
# in the definition file via Vi or
# Nano editor and then run kubectl apply command to update the image :-

What does the READY column in the output of the kubectl get pods command indicate?

Untitled

# Delete any one of the 4 PODs.

# run replicaset
kubectl create -f replicaset.yaml

kubectl create -f deployment-definition.yaml

# Create a new Deployment with the below attributes using your own deployment definition file.
# Name: httpd-frontend;
# Replicas: 3;
# Image: httpd:2.4-alpine

먼저, 명령어를 사용할 때 아주 유용한 두 가지 옵션을 알아둬야 해요:

  1. -dry-run: 이 옵션은 명령어를 실행했을 때 리소스가 바로 생성되지 않게 합니다. 즉, 명령어가 올바른지, 리소스를 생성할 수 있는지만 확인하고 싶을 때 -dry-run=client 옵션을 사용하세요.
  2. o yaml: 이 옵션은 리소스 정의를 YAML 형식으로 화면에 출력합니다.

이 두 옵션을 조합해서 빠르게 리소스 정의 파일을 생성한 다음, 필요에 따라 수정하여 리소스를 생성할 수 있어요. 이 방법을 사용하면 처음부터 파일을 만들 필요가 없어서 편리하죠.

POD 생성​

  • NGINX Pod 생성: kubectl run nginx --image=nginx
  • POD 매니페스트 YAML 파일 생성 (생성하지 않음, -dry-run): kubectl run nginx --image=nginx --dry-run=client -o yaml

Deployment 생성​

  • Deployment 생성: kubectl create deployment --image=nginx nginx
  • Deployment YAML 파일 생성 (생성하지 않음, -dry-run): kubectl create deployment --image=nginx nginx --dry-run=client -o yaml
  • 4개의 복제본이 있는 Deployment 생성: kubectl create deployment nginx --image=nginx --replicas=4
  • Deployment 스케일링: kubectl scale deployment nginx --replicas=4
  • YAML 파일 저장 및 수정 후 Deployment 생성: kubectl create deployment nginx --image=nginx --dry-run=client -o yaml > nginx-deployment.yaml

Service 생성​

  • ClusterIP 타입의 redis-service Service 생성하여 포드 redis를 6379 포트에 노출: kubectl expose pod redis --port=6379 --name=redis-service --dry-run=client -o yaml
  • NodePort 타입의 nginx Service 생성하여 포드 nginx의 80 포트를 노드의 30080 포트에 노출: kubectl expose pod nginx --type=NodePort --port=80 --name=nginx-service --dry-run=client -o yaml

pod 생성​

kubectl expose pod redis --port=6379 --name redis-service service/redis-service exposed

kubectl create deployment webapp --image=kodekloud/webapp-color --replicas=3

kubectl run custom-nginx --image=nginx --port=8080

Create a new deployment called redis-deploy in the dev-ns namespace with the redis image. It should have 2 replicas.

kubectl create deployment redis-deploy —image=redis —replicas=2 —namespace=dev-ns

pod를 특정 node에 배포하기​

· 6 min read

OS update 시 특정 node에 존재하는 pod를 치워줘야 한다.​

kubectl drain node-1

kubectl cordon node-1

We need to take node01 out for maintenance. Empty the node of all applications and mark it unschedulable.

kubectl drain node01 --ignore-daemonsets

The maintenance tasks have been completed. Configure the node node01 to be schedulable again.

#Mark node as schedulable.
kubectl uncordon NODE

Cluster Upgrade​

  1. 마스터 노드 drain
  2. 마스터 노드의 kubeadm 업그레이드
  3. 마스터 노드의 kubectl, kubelet 업그레이드
  4. 마스터 노드 uncordon
  5. 워커 노드 drain
  6. 워커 노드의 kubeadm 업그레이드
  7. 워커 노드의 kubectl, kubelet 업그레이드(kubectl이 없을 경우 kubelet만 업그레이드) kubectl은 단순 클라이언트 도구이기 때문에 워커 노드에 없는 경우도 있다. 이 경우 kubelet만 업그레이드 한다.
  8. 워커 노드 uncordon
# 마스터에서 작업
ssh master

# 1.29.x-00에서 x를 최신 패치 버전으로 바꾼다.
apt-mark unhold kubeadm && \
apt-get update && apt-get install -y kubeadm=1.29.x-00 && \
apt-mark hold kubeadm

# 다운로드 된 버전 확인
kubeadm version

# 업그레이드 계획 확인
# 클러스터를 업그레이드할 수 있는지를 확인하고, 업그레이드할 수 있는 버전을 가져온다. 또한 컴포넌트 구성 버전 상태가 있는 표를 보여준다.
kubeadm upgrade plan

# 이 업그레이드를 위해 선택한 패치 버전으로 x를 바꾼다.
sudo kubeadm upgrade apply v1.29.x

# 마스터에서 나오기
exit

# <node-to-drain>을 드레인하는 노드의 이름으로 바꾼다.cordon된다.
kubectl drain <node-to-drain> --ignore-daemonsets

# 마스터에서 작업
ssh master

# 노드안에서 kubelet 및 kubectl을 업그레이드한다. 1.29.x-00의 x를 최신 패치 버전으로 바꾼다
apt-mark unhold kubelet kubectl && \
apt-get update && apt-get install -y kubelet=1.29.x-00 kubectl=1.29.x-00 && \
apt-mark hold kubelet kubectl

# kubelet 재시작
sudo systemctl daemon-reload
sudo systemctl restart kubelet

# 마스터에서 나오기
exit

# uncordon 해주기
kubectl uncordon <node-to-uncordon>

k get nodes

# worker node 차례로 작업..
apt-get upgrade -y kubeadm=1.12.0-00
# 클러스터 버전이 업그레이드가 되었다.
kubeadm upgrade apply v1.12.0
# kubelet 버전을 업그레이드 해야한다. (Master부터)
apt-get upgrade -y kubelet=1.12.0-00
systemctl restart kubelet
kubectl uncordon

# 워커노드 드레인
kubectl drain node-1

# 워커노드 업그레이드
apt-get upgrade -y kubeadm=1.12.0-00
apt-get upgrade -y kubelet=1.12.0-00

kubeadm upgrade node config --kubelet-version v1.12.0
systemctl restart kubelet

강의 내용에 따르면..​

# control plane으로 접속 (master 노드)
ssh controlplane

# 버전 살피기
cat /etc/*release*

apt-cache madison kubeadm

# 업그레이드를 한다고 해도 바로 되진 않음.
sudo kubeadm upgrade apply v.1.25.10

# ControlPlane에 위치한 pod들을 빼낼 것
kubectl drain controlplane --ignore-daemonset

# kubeadm 업그레이드 하기, 1.29.0-00에서 x를 최신 패치 버전으로 바꾼다.
sudo apt-mark unhold kubeadm && \
sudo apt-get update && sudo apt-get install -y kubeadm='1.29.0-*' && \
sudo apt-mark hold kubeadm
# kubeadm 버전 확인 1.29.0
kubeadm version

# kubelet 업그레이드 하기, 1.29.x-00에서 x를 최신 패치 버전으로 바꾼다.
sudo apt-mark unhold kubelet kubectl && \
sudo apt-get update && sudo apt-get install -y kubelet='1.29.0-*' kubectl='1.29.0-*' && \
sudo apt-mark hold kubelet kubectl

# Restart Kubelet
systemctl restart daemon-reload
systemctl restart kubelet

# uncordon node
kubectl uncordon controlplane

exit

# control node01으로 접속 (worker 노드)
ssh node01

sudo kubeadm upgrade node

# node01에 위치한 pod들을 빼낼 것
kubectl drain controlplane --ignore-daemonset

# kubelet 업그레이드 하기, 1.29.x-00에서 x를 최신 패치 버전으로 바꾼다.
apt-mark unhold kubeadm && \
apt-get update && apt-get install -y kubeadm=1.25.x-00 && \
apt-mark hold kubeadm

# Restart Kubelet
systemctl restart daemon-reload
systemctl restart kubelet

# uncordon node
kubectl uncordon node01

exit

Backup and Restore Methods​

모든 포드 배포 서비스의 명령어 가져오기

kubectl get all -all namespaces -o yaml > all-deploy-sevrice.yaml

What is the version of ETCD running on the cluster?

Check the ETCD Pod or Process

kubectl get pods -A
> kube-system etcd-controlplane 1/1 Running 0 2m38s

kubectl logs -n kube-system etcd-controlplane | grep -i 'etcd-version'

Where is the ETCD server certificate file located? > /etcd/kubernetes/pki/etcd/server.crt

Where is the ETCD CA Certificate file located? > /etcd/kubernetes/pki/etcd/ca.crt

The master node in our cluster is planned for a regular maintenance reboot tonight. While we do not anticipate anything to go wrong, we are required to take the necessary backups. Take a snapshot of the ETCD database using the built-in snapshot functionality.

Store the backup file at location /opt/snapshot-pre-boot.db

ETCDCTL_API=3 etcdctl --endpoints=https://127.0.0.1:2379 \
--cacert=/etc/kubernetes/pki/etcd/ca.crt --cert=/etc/kubernetes/pki/etcd/server.crt --key=/etc/kubernetes/pki/etcd/server.key \
snapshot save /opt/snapshot-pre-boot.db

Luckily we took a backup. Restore the original state of the cluster using the backup file.

보통 host pod들은 /var/lib/etcd에 저장되어있다. 다른 곳을 설정해주어야한다.

ETCDCTL_API=3 etcdctl --data-dir /var/lib/etcd-from-what-iwant-dir snapshot restore /opt/snapshot-pre-boot.db

vi /etc/kubernetes/manifests/etcd.yaml

· 6 min read

Rolling update and Rollback​

Revision 단위로 버전을 관리하여 업데이트와 롤백 버전을 관리하게 된다.

롤아웃 버전 알아보기

kubectl rollout status deployment/my-app-deplpoyment

kubectl rollout history deployment/my-app-deplpoyment

2가지 타입의 업데이트 전략이 존재함.

  1. recreate
  1. rollingupdate

Alt text Deployment 안 Replica Set이 생기며, Pod 한개씩 대체되기 시작한다.

Rollback​

롤백을 하게 되면 오래전의 Replica Set을 불러오게 된다.

kubectl rollout undo deployment/my-app-deployment

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.

kubectl edit deployment frontend
# 후 버전을 바꾸면 된다.

Change the deployment strategy to Recreate

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

kubectl edit deployment frontend
# 후 버전을 바꾸고 strategt를 Recreate로 변경해야함.

Docker 환경 변수 넣기​

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.

controlplane ~/webapp-color-2 ➜  cat webapp-color-pod.yaml 
apiVersion: v1
kind: Pod
metadata:
name: webapp-green
labels:
name: webapp-green
spec:
containers:
- name: simple-webapp
image: kodekloud/webapp-color
command: ["--color","green"]

controlplane ~/webapp-color-2 ➜ cat Dockerfile
FROM python:3.6-alpine

RUN pip install flask

COPY . /opt/

EXPOSE 8080

WORKDIR /opt

ENTRYPOINT ["python", "app.py"]

CMD ["--color", "red"]

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.

controlplane ~/webapp-color-3 ➜  cat Dockerfile 
FROM python:3.6-alpine
RUN pip install flask
COPY . /opt/
EXPOSE 8080
WORKDIR /op
ENTRYPOINT ["python", "app.py"]
CMD ["--color", "red"]

controlplane ~/webapp-color-3 ➜ cat webapp-color-pod-2.yaml
apiVersion: v1
kind: Pod
metadata:
name: webapp-green
labels:
name: webapp-green
spec:
containers:
- name: simple-webapp
image: kodekloud/webapp-color
command: ["python", "app.py"]
args: ["--color", "pink"]

ConfigMap​

pod의 env 변수 설정을 하게 도와준다. 보통 서버의 환경(검증,운영계), ~~ip주소 혹은 DB 계정정보(Secret 사용)~~를 지정해주면 좋을것이다.

# config-map.yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: **app-config**
data:
SERVER_ENV: prd
POSTGRE_URL: 127.0.0.1:5432

다음과 같이 설정되있으면, pod definition때 ConfigMap을 삽입해보자면, configMapRef란 곳에 configMap을 여러개 삽입할 수 있게 한다.

apiVersion: v1
kind: Pod
metadata:
name: webapp
spec:
containers:
- name: webapp
image: webapp
envFrom:
- configMapRef:
name: **app-config**

실습​

env APP_COLOR 가 green 인 pod을 띄우시오

apiVersion: v1
kind: Pod
metadata:
name: webapp-color
labels:
name: webapp-color

spec:
containers:
name: kodekloud/webapp-color
image: webapp-color
- env:
- name: APP_COLOR
value: green

How many ConfigMaps exists in the default namespace?

kubectl get ConfigMaps

Secret​

ConfigMap이 아닌 민감정보 DB 계정정보의 경우 Secret을 통해 저장한다. key value에서 base64로 인코딩된 값을로 저장한다.

apiVersion: v1
kind: Secret
metadata:
name: **app-secret**
data:
DB_HOST: cgjfDfg=
DB_PASSWORD: cFghfi

echo -n ‘root’ | base64 라고 명령어를 치면 base64 인코딩된 값이 추출된다.

apiVersion: v1
kind: Pod
metadata:
name: webapp
spec:
containers:
- name: webapp
image: webapp
envFrom:
- secretRef:
name: **app-secret**

Encrypting Secret Data At Rest ← 먼소린지 모르겟..​

apt-get install etcd-client

ls /etc/kubernetes/pki/etcd

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/my-secret

ls /etc/kubernetes/manifests/

Multi Container Pod​

Alt text

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

kubectl -n elastic-stack exec -it app -- cat /log/app.log

Edit the pod in the elastic-stack namespace 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/

Requirements

  • 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
---
apiVersion: v1
kind: Pod
metadata:
name: app
namespace: elastic-stack
labels:
name: app
spec:
containers:
- name: app
image: kodekloud/event-simulator
volumeMounts:
- mountPath: /log
name: log-volume

- name: sidecar
image: kodekloud/filebeat-configured
volumeMounts:
- mountPath: /var/log/event-simulator/
name: log-volume

volumes:
- name: log-volume
hostPath:
# directory location on host
path: /var/log/webapp
# this field is optional
type: DirectoryOrCreate

Init Container​

initContainers의 역할: 때로는 팟이 시작할 때만 필요한 일시적 작업이 있습니다. 이런 작업을 위해 **initContainers**를 사용합니다. 이 컨테이너들은 메인 애플리케이션이 시작하기 전에 필요한 사전 작업(예: 필요한 코드를 끌어오거나 외부 서비스의 가용성 확인)을 수행합니다.

상황: orange pod의 issue를 fix 하시오

# 무슨 일인지 살펴보자
kubectl describe pod orange

# 로그를 살펴보자
kubectl logs orange
kubectl logs orange -c init-myservice

· 4 min read

Labels and Selectors​

We have deployed a number of PODs. They are labelled with tier, env and bu. How many PODs exist in the dev environment (env)?

kubectl get pods --selector env=dev

경험에 따르면, CPU sort 하는 것도 시험에 나온다고 하였다.

kubectl top po -A --sort-by=cpu

How many PODs are in the finance business unit (bu)?

kubectl get pods --selector bu=finance

How many objects are in the prod environment including PODs, ReplicaSets and any other objects?

kubectl get all --selector env=prod

Identify the POD which is part of the prod environment, the finance BU and of frontend tier?

kubectl get all --selector env=prod,bu=finance,tier=frontend

replicaset-definition.yaml

apiVersion : apps/v1
kind : ReplicaSet
metadata:
name: simple-webapp
labels:
app: app1
function: Front-end
spec:
replicas: 3
selector:
matchLabels:
app: App1
template:
metadata:
labels:
app: App1
function: Front-end
spec:
containers:
- name : simple-webapp
image: simple-webapp

service-definition.yaml

apiVersion : v1
kind : Service
metadata:
name: my-service
spec:
selector:
app: App1
ports:
- protocol:TCP
port : 80
targetPort: 9376

Node Selector​

kubectl label nodes node-name label-key=label-value

ex) kubectl label nodes node-1 size=Large 라고 설정을 하고

spec:
containers:
- name : data-processor
image: data-processor
nodeSelector: Large

Node Affinitiy​

Node Affinity Type​

requiredDuringSchedulingIngnoredDuringExecution - Type1 : 강제성이 있음.
preferredDuringSchedulingIngnoredDuringExecution - Type2 : 어쩔 수 없으면 함.

Apply a label color=blue to node node01

kubectl label nodes node01 color=blue

Create a new deployment named blue with the nginx image and 3 replicas.

kubectl create deployment blue --image=nginx
kubectl scale deployment/blue --replicas=3

Which nodes can the pods for the blue deployment be placed on?

Make sure to check taints on both nodes!

kubectl describe node controlplane | grep Taints
kubectl describe node node1 | grep Tains

check Taint both!

Create a new deployment named red with the nginx image and 2 replicas, and ensure it gets placed on the controlplane node only.

Use the label key - node-role.kubernetes.io/control-plane - which is already set on the controlplane node.

kubectl create deployment red --image=nginx --replicas=2 --dry-run=client -o yaml  

kubectl create deployment red --image=nginx --replicas=2 --dry-run=client -o yaml > red.yaml


affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: disktype
operator: In
values:
- ssd

Resource Requirements and Limit​

개념) Kube-Scheduler가 노드의 Mem / CPU를 보고 pod를 Node에 할당

할당 단위​

CPU : 1m(최소 단위 이 밑으로 내려갈 수 없음.) 1 (CPU Core를 의미)

The elephant pod runs a process that consumes 15Mi of memory. Increase the limit of the elephant pod to 20Mi.

Delete and recreate the pod if required. Do not modify anything other than the required fields.

kubectl create pod elephant --image=polinux/stress  --dry-run=client -o yaml > elephant.yaml

kubectl replace -f elephant.yaml --force

Daemon Sets​

모든 노드에 각각 존재함. 모니터링에서 사용됨.

kube-scheduler의 영향을 받지 않음

 kubectl get daemonsets --all-namespaces

Which namespace is the kube-proxy Daemonset created in?

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

kubectl describe daemonset kube-flannel-ds --namespace=kube-flannel

Deploy a DaemonSet for FluentD Logging.

Name: elasticsearch

Namespace: kube-system

Image: registry.k8s.io/fluentd-elasticsearch:1.20 kubectl create Daemonset elasticsearch --namespace=kube-system --image=registry.k8s.io/fluentd-elasticsearch:1.20 -o yaml > elasticsearch.yaml

kubectl create Daemonset은 없음

kubectl create deployment elasticsearch --namespace=kube-system --image=registry.k8s.io/fluentd-elasticsearch:1.20 --dry-run=client -o yaml

kubectl create deployment elasticsearch --namespace=kube-system --image=registry.k8s.io/fluentd-elasticsearch:1.20 --dry-run=client -o yaml > fluentD.yaml

Static Pod​

각 node 안 kubelet에서 생성을 함.

kube-scheduler의 영향을 받지 않음

pod.yaml은 etc/kubernetes/manifests 에 존재하며 이를 가져온다.

Multiple Scheduler​

scheduler 만들기

apiVersion: kubescheduler.config.k8s.io/v1
kind: KubeSchedulerConfiguration
profiles:
- schedulerName: my-scheduler
leaderElection:
leaderElect: false

Pod에 custom scheduler 적용하는 방법

apiVersion : v1
kind : Pod
metadata:
name: nginx
spec:
containers:
- image: nginx
name: nginx
shcedulerName: my-custom-scheduler

View Events​

kubectl get evnets -o wide

kubectl logs my-custom-scheulder --name-space=kube-system

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

kubectl get pods --namespace=kube-system

kubectl get pods -A

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.

Scheduling 4단계​

Scheduling Queue → Filtering → Scoring → Binding

Scheduling Queue : PrioritySort

Filtering : NodeResourcesFit, NodeName, NodeUnshcedulable

Scoring : NodeResourcesFit, ImageLocality

Binding : DefaultBinder

· One min read
Gao Wei

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque elementum dignissim ultricies. Fusce rhoncus ipsum tempor eros aliquam consequat. Lorem ipsum dolor sit amet