본문 바로가기

Kubernates

쿠버네티스 따배씨 강의

https://youtu.be/KdATmTulf7s?si=V7tN7jU5KxUvaRcE

 

 

** 강의 내용의 목차를 중심으로 공식 docs 와 참고 명령어 정리 

1. ETCD

 

원하는 노드로 우선 이동

#whoami

#sudo -i

ETCDCTL_API=3 etcdctl --endpoints=https://127.0.0.1:2379 \
  --cacert=<trusted-ca-file> --cert=<cert-file> --key=<key-file> \
  snapshot save <backup-file-location>

 

#sudo ETCDCTL_API

 

Restore

ETCDCTL_API=3 etcdctl --data-dir /var/lib/etcd-new snapshot restore snapshot.db

 

#sudo vi /etc/kubernetes/manifest/etcd.yaml

hostpath 변경 -> var/lib/etcd-new

 

#sudo docker ps -a | grep etcd

2. Pod 생성하기

 

클러스터 우선 설정 * 

#kubectl config use-context hello 

#kubectl config current-context

env 설정하면서 파드 생성 *

#kubectl run pod --image=nginx --env=my=name -n namespace --dry-run=client

 

3. Static Pod 

ssh 로 원하는 Node 로 이동 후 해당 명령어 수정 하여 static pod 생성 ( 장소는 이미 지정 )

#whoami

#sudo -i

#cat var/lib/kubelet/config.yaml 

(staticpodpath 참고)

 

mkdir -p /etc/kubernetes/manifests/
cat <<EOF >/etc/kubernetes/manifests/static-web.yaml
apiVersion: v1
kind: Pod
metadata:
  name: static-web
  labels:
    role: myrole
spec:
  containers:
    - name: web
      image: nginx
      ports:
        - name: web
          containerPort: 80
          protocol: TCP
EOF

 

4. Multi Container Pod

apiVersion: v1
kind: Pod
metadata:
  name: nginx
spec:
  containers:
  - name: nginx
    image: nginx:1.14.2
  - name: nginx2
    image: nginx:1.14.3
  - name: nginx3
    image: nginx:1.14.4

 

5. Side-car Container Pod

빨리 파드 지우는법

#k delete pod name --force

 

https://kubernetes.io/docs/concepts/cluster-administration/logging/

 

Logging Architecture

Application logs can help you understand what is happening inside your application. The logs are particularly useful for debugging problems and monitoring cluster activity. Most modern applications have some kind of logging mechanism. Likewise, container e

kubernetes.io

 

6. Deployment & Pod scale

#k scale deployment hello --replicas=3

 

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  labels:
    app: nginx
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.14.2
        ports:
        - containerPort: 80

 

7. Rolling Update & Rollback

#k set image deployment nginx-deploy nginx(컨테이너 이름)=nginx:1.16.2 --record

#k rollout history deployment nginx-deploy

#k rollout status deployment nginx-deploy

#k rollout undo deployment nginx-deploy

 

 

8. Node Selector

#k get nodes --show-labels

#k get nodes -L key

 

apiVersion: v1
kind: Pod
metadata:
  name: nginx
  labels:
    env: test
spec:
  containers:
  - name: nginx
    image: nginx
    imagePullPolicy: IfNotPresent
  nodeSelector:
    disktype: ssd

9. Node 관리

#k get pods -o wide -A

#k drain node01 --ignore-daemonsets --force 

 

#k cordon node01

#k uncordon node02

10. 노드 정보 수집

#k get nodes | grep -i -w ready

#echo "3" > 파일저장소

 

11. Deployment & Expose the Service

apiVersion: v1
kind: Pod
metadata:
  name: nginx
  labels:
    app.kubernetes.io/name: proxy
spec:
  containers:
  - name: nginx
    image: nginx:stable
    ports:
      - containerPort: 80
        name: http-web-svc

---
apiVersion: v1
kind: Service
metadata:
  name: nginx-service
spec:
  selector:
    app.kubernetes.io/name: proxy
  ports:
  - name: name-of-service-port
    protocol: TCP
    port: 80
    targetPort: http-web-svc

12. Pod Log 추출

 

#k logs app | grep 'file not found' > 저장소

13. CPU 사용량 높은 Pod 검색

#k top pods -l label=search --sort-by=cpu

14. init 컨테이너를 포함한 Pod 운영

init 완료 후 작동으로 기본동작 

apiVersion: v1
kind: Pod
metadata:
  name: myapp-pod
  labels:
    app.kubernetes.io/name: 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.$(cat /var/run/secrets/kubernetes.io/serviceaccount/namespace).svc.cluster.local; do echo waiting for myservice; sleep 2; done"]

15. NodePort 서비스 생성 

apiVersion: v1
kind: Service
metadata:
  name: my-service
spec:
  type: NodePort
  selector:
    app.kubernetes.io/name: MyApp
  ports:
    - port: 80
      # By default and for convenience, the `targetPort` is set to
      # the same value as the `port` field.
      targetPort: 80
      # Optional field
      # By default and for convenience, the Kubernetes control plane
      # will allocate a port from a range (default: 30000-32767)
      nodePort: 30007

16. ConfigMap 운영

환경변수 or 볼륨마운트 파일 형식

kubectl create configmap special-config --from-literal=special.how=very

 

apiVersion: v1
kind: Pod
metadata:
  name: dapi-test-pod
spec:
  containers:
    - name: test-container
      image: registry.k8s.io/busybox
      command: [ "/bin/sh", "-c", "env" ]
      env:
        # Define the environment variable
        - name: SPECIAL_LEVEL_KEY
          valueFrom:
            configMapKeyRef:
              # The ConfigMap containing the value you want to assign to SPECIAL_LEVEL_KEY
              name: special-config
              # Specify the key associated with the value
              key: special.how
apiVersion: v1
kind: Pod
metadata:
  name: dapi-test-pod
spec:
  containers:
    - name: test-container
      image: registry.k8s.io/busybox
      command: [ "/bin/sh", "-c", "ls /etc/config/" ]
      volumeMounts:
      - name: config-volume
        mountPath: /etc/config
  volumes:
    - name: config-volume
      configMap:
        # Provide the name of the ConfigMap containing the files you want
        # to add to the container
        name: special-config

17. Secret 운영

환경변수 or 볼륨마운트 파일 형식

데이터 자료가 따로 구성설정 된다는점이 configmap 과 비슷하지만 secret 의 value 값은 base64 로 인코딩

#echo "a" | base64

#echo "$%3" | base64 -d

 

apiVersion: v1
kind: Pod
metadata:
  name: mypod
spec:
  containers:
  - name: mypod
    image: redis
    volumeMounts:
    - name: foo
      mountPath: "/etc/foo"
      readOnly: true
  volumes:
  - name: foo
    secret:
      secretName: mysecret
apiVersion: v1
kind: Pod
metadata:
  name: envvars-multiple-secrets
spec:
  containers:
  - name: envars-test-container
    image: nginx
    env:
    - name: BACKEND_USERNAME
      valueFrom:
        secretKeyRef:
          name: backend-user
          key: backend-username
    - name: DB_USERNAME
      valueFrom:
        secretKeyRef:
          name: db-user
          key: db-username

18. Ingress 구성

마이크로서비스같은 역할 구축할때 rule 필요

 

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: minimal-ingress
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /
spec:
  ingressClassName: nginx-example
  rules:
  - http:
      paths:
      - path: /testpath
        pathType: Prefix
        backend:
          service:
            name: test
            port:
              number: 80

19. Persistent Volume 생성

apiVersion: v1
kind: PersistentVolume
metadata:
  name: pv0003
spec:
  capacity:
    storage: 5Gi
  volumeMode: Filesystem
  accessModes:
    - ReadWriteOnce
  persistentVolumeReclaimPolicy: Recycle
  storageClassName: slow
  mountOptions:
    - hard
    - nfsvers=4.1
  nfs:
    path: /tmp
    server: 172.17.0.2

 

 

20. Persistent Volume Claim 을 사용하는 Pod 운영

pvc 생성 & pvc 에 pod 연결

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: myclaim
spec:
  accessModes:
    - ReadWriteOnce
  volumeMode: Filesystem
  resources:
    requests:
      storage: 8Gi
  storageClassName: slow
apiVersion: v1
kind: Pod
metadata:
  name: mypod
spec:
  containers:
    - name: myfrontend
      image: nginx
      volumeMounts:
      - mountPath: "/var/www/html"
        name: mypd
  volumes:
    - name: mypd
      persistentVolumeClaim:
        claimName: myclaim

21. Check Resource Information

https://kubernetes.io/pt-br/docs/reference/kubectl/cheatsheet/

 

kubectl Cheat Sheet

Esta página contém uma lista de comandos kubectl e flags frequentemente usados. Kubectl Autocomplete BASH source <(kubectl completion bash) # configuração de autocomplete no bash do shell atual, o pacote bash-completion precisa ter sido instalado prime

kubernetes.io

 

# --sort-by=

 

22. Kubernets Upgrade

#k get nodes 로 버전 확인

(drain masternode -> uncordon after the upgrade)

 

#sudo -i

 

1// Determine which version to upgrade to ->

apt update
apt-cache madison kubeadm

 

2// Upgrade kubeadm _>

apt-mark unhold kubeadm && \
apt-get update && apt-get install -y kubeadm='1.29.x-*' && \
apt-mark hold kubeadm

#kubeadm version

 

3// 마스터 구성요소 업그레이드 

 

#kubeadm upgrade plan

# sudo kubeadm upgrade apply v1.29.x

 

4// drain 작업

#exit

#kubectl drain <node-to-drain> --ignore-daemonsets

#ssh master

 

5// kubelet kubectl 업그레이드

apt-mark unhold kubelet kubectl && \
apt-get update && apt-get install -y kubelet='1.29.x-*' kubectl='1.29.x-*' && \
apt-mark hold kubelet kubectl
sudo systemctl daemon-reload
sudo systemctl restart kubelet

 

6// uncordon 

#exit

#kubectl uncordon <node-to-uncordon>

#k get nodes

23. Trouble Shooting 1 & 24. Trouble Shooting 2

woker node - 엔진 / kubelet / kube-proxy / CNI 상태 확인 to be ready

#sudo i

 

#systemctl status docker #systemctl enable --now docker

#systemctl status kubelet #systemctl enable --now kubelet

#exit #k get pods -n kube-system -o wide

25. User Role Binding

#kubectl create role pod-reader --verb=get --verb=list --verb=watch --resource=pods

#kubectl create rolebinding bob-admin-binding --clusterrole=admin --user=bob --namespace=acme

 

#kubectl config set-credentials myuser --client-key=myuser.key --client-certificate=myuser.crt --embed-certs=true

#kubectl config view

#kubectl config set-context myuser --cluster=kubernetes --user=myuser

26. User Cluster Role

#kubectl create clusterrole pod-reader --verb=get,list,watch --resource=pods

#kubectl create clusterrolebinding root-cluster-admin-binding --clusterrole=cluster-admin --user=root

27. ServiceAccount Role Binding

#k create serviceaccout my-sa -n ns

#kubectl create role pod-reader --verb=get --verb=list --verb=watch --resource=pods

#kubectl create rolebinding myapp-view-binding --role=view --serviceaccount=ns:myapp --namespace=ns

28. ServiceAccount Cluster Role Binding

#k create serviceaccout my-sa -n ns

#kubectl create clusterrole pod-reader --verb=get --verb=list --verb=watch --resource=pods

#kubectl create clusterrolebinding myapp-view-binding --role=view --serviceaccount=ns:myapp --namespace=ns

29. Kube-DNS

#k expose pod podname --name=servicename --port=80 targetport=80 

Service DNS #nslookup - nginx-name.default.svc.cluster.local

Pod DNS #nslookup - 10-244-1-163.default.pod.cluster.local

 

#k run test-nslookup --image=busybox:1.28 -it --restart=Never --rm -- nslookup ~

30. Network Policy

#k get namespaces hello --show-labels (네임스페이스에 대한 레이블)

#k get pod -n hello --show-lables (네임스페이스 내부의 파드에 관한 레이블)

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: test-network-policy
  namespace: default
spec:
  podSelector:
    matchLabels:
      role: db
  policyTypes:
  - Ingress
  - Egress
  ingress:
  - from:
    - ipBlock:
        cidr: 172.17.0.0/16
        except:
        - 172.17.1.0/24
    - namespaceSelector:
        matchLabels:
          project: myproject
    - podSelector:
        matchLabels:
          role: frontend
    ports:
    - protocol: TCP
      port: 6379
  egress:
  - to:
    - ipBlock:
        cidr: 10.0.0.0/24
    ports:
    - protocol: TCP
      port: 5978