💡 이 글은 쿠버네티스 기본 내용을 단권화하여 정리한 글이다.
📌 모든 내용은 자세하게 설명하지 않고, CKA 합격에 포커싱하여 간략하게 정리한다.
⌨️ UDemy의 Certified Kubernetes Administrator (CKA) with Practice Tests를 기반으로 한다.
시작일 : 2023-10-18
최근 수정일 : 2024-06-17
종료 :
📌 명령어 정리
| 명령어 | 설명 |
| kubectl create -f <file name>.yml | 리소스를 처음 생성할 때 사용 기존에 동일한 이름의 리소스가 이미 존재하는 경우 에러가 발생 -f는 파일 이름을 전달할 때 사용하는 옵션 관리 그룹 내에 파드를 생성 |
| kubectl create -f <file name>.yml --namespace=dev | 네임스페이스 옵션 |
| kubectl apply -f <file name>.yml | 리소스를 처음 생성할 때 사용 기존에 동일한 이름의 리소스가 이미 존재하는 경우 해당 리소스를 변경 |
| kubectl run <name> --image=<container-image> | 새로운 파드 or Deployment를 생성하고 클러스터에 배포함 단일 파드 생성 및 관리(간단한 테스트 시 사용) |
| kubectl get <resource_type> | 리소스를 조회, all은 모든 리소스를 조회 |
| kubectl get <resourcename> --all-namespaces | 모든 네임스페이스에서 리소스 조회 |
| kubectl get pods -o wide | 파드 조회 중 더 많은 정보를 볼 수 있음 |
| kubectl get pods <pod name> -o yaml > <new.yaml> | -o output이란 뜻으로 기존의 pod yaml 정보를 새로운 yaml로 옮김 |
| kubectl get pods --namespace=kube-system |
쿠버네티스에서 만드는 기본 파드 조회 |
| kubectl get pods -A | 네임스페이스를 첫번째 컬럼 구분으로 모든 파드 조회 |
| kubectl describe <resource_type> <resource_name> | 파드 정보 조회(컨테이너 정보, 노드 정보 등 볼 수 있음) |
| kubectl describe <resource_type> <resource_name> -n <namespace_name> or --namespace=<namespace_name> | describe를 볼 때 네임스페이스가 다르면 찾을 수 없다는 에러가 남 |
| kubecrl get pod <pod name> -o yaml | 해당 파드의 설정 정보를 yaml로 보여줌, json으로 하면 json으로 보여줌 |
| kubectl delete <resource_type> <resource_name> | 파드 삭제, --all (전부 삭제) |
| kubectl edit <resource_type> <resource_name> | 쿠버네티스 클러스터의 리소스를 직접 편집 |
| kubectl scale <resource_type> <resource_name> --replicas=<number> | 쿠버네티스 클러스터의 특정 리소스(Deployment, ReplicaSet, ReplicaController, StatefulSet)에 대한 복제본(replicas)의 수를 조정 |
| kubectl run <name> --image=<image> | 쿠버네티스 클러스터에서 특정 이미지를 기반으로 새로운 파드를 생성, 파드만!! |
| kubectl create configmap <config-name> --from-literal=<key>=<value> | 컨피그맵 생성(문자) EX) kubectl create configmap appConfig \ --from-literal==COLOR=blue \ --from-literal==MOD=prod |
| kubectl create configmap <config-name> -- from-file=<path-to-file> | 컨피그맵 생성(파일) EX) kubectl create configmap appConfig \ --from-file=appConfig.properties |
| kubectl create secret generic <secret-name> --from-literal=<key>=<value> | 시크릿 생성(문자) EX) kubectl create secret generic \ app-secret --from-literal=DB_Host=mysql |
| kubectl create secret generic <secret-name> -- from-file=<path-to-file> | 시크릿 생성(파일) EX) kubectl create secret generic \ app-secret --from-file=app_secret.properties |
| kubectl -n kube-system logs etcd-controlplane | grep -i 'etcd-version' | etcd log에서 etcd-version 찾기 |
| kubectl -n kube-system describe pod etcd-controlplane | grep Image: | kube-system namespace에서 etcd-controlplane pod의 세부 정보 중 image 정보를 불러온다. |
| 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 |
백업하기 Use the etcdctl snapshot save command. --endpoints: Optional Flag, points to the address where ETCD is running (127.0.0.1:2379) --cacert: Mandatory Flag (Absolute Path to the CA certificate file) --cert: Mandatory Flag (Absolute Path to the Server certificate file) --key: Mandatory Flag (Absolute Path to the Key file) |
| ETCDCTL_API=3 etcdctl --data-dir /var/lib/etcd-from-backup \ snapshot restore /opt/snapshot-pre-boot.db |
복원하기 |
| kubectl config get-cluster | 현재 설정된 Kubernetes 클러스터의 이름과 해당 클러스터의 구성 정보가 출력 |
| kubectl config use-context <cluster-name> | 현재 작업하는 Kubernetes 클러스터를 변경 |
| ssh <node-name> / logout / ps -ef | grep etcd | kubectl get node를 통해 나온 노드 중 선택하여 안으로 진입/ ssh 연결 종료 / ssh 연결 후 etcd 찾기(External etcd) |
| kubectl get pods -n kube-system | grep etcd | "kube-system" 네임스페이스에 있는 Pod 목록을 가져온 후, 그 중에서 "etcd"라는 키워드를 포함하는 Pod를 필터링하는 명령어(Stacked etcd) |
| openssl x509 -in /etc/kubernetes/pki/apiserver.crt -text | 이 명령어를 사용하여 /etc/kubernetes/pki/apiserver.crt 경로에 있는 X.509 인증서 파일의 내용을 텍스트 형식으로 확인할 수 있다. 이를 통해 인증서의 발급자(CA), 유효 기간, 공개 키, 서명 알고리즘 등 다양한 정보를 확인할 수 있다. |
| kubectl get csr | Kubernetes 클러스터에서 Certificate Signing Request(CSR)을 조회하는 명령어 CSR은 인증 기관에 서명된 인증서를 요청하기 위해 사용되는 정보를 포함한 보안 인증 요청이다. 이 명령어를 실행하면 현재 클러스터에서 보류 중인 CSR의 목록을 확인할 수 있다. |
| kubectl certificate approve <csr-name> | csr 승인하기 |
| kubectl certificate deny <csr-name> | csr 거절하기 |
| kubectl delete csr <csr-name> | csr 삭제하기 |
| kubectl get csr <csr-name> -o yaml | 해당 csr의 설정 정보를 yaml 파일로 보여줌 |
| kubectl config current-context --kubeconfig=<config-yaml-path> | --kubeconfig 플래그를 사용하여 특정 kubeconfig 파일을 지정하고, 현재 활성화된 컨텍스트를 확인 |
| kubectl config use-context <switch-context-name> --kubeconfig=<config-yaml-path> | --kubeconfig 플래그를 사용하여 특정 kubeconfig 파일을 지정하고, 특정 컨텍스트를 활성화 |
| cp <custom-kube-config> ~/.kube/config | 커스텀으로 만든 config 파일을 default kubeconfig로 Overwrite |
| kubectl describe pod <pod-name> -n <namespace-name> | 특정 네임스페이스 내에 pod에서 authorization-mode를 확인할 수 있음 |
| kubectl get roles | 위 명령어만 입력한다면 default 네임스페이스에 존재하는 역할 목록을 확인할 수 있다. |
| kubectl get roles --all-namespaces or kubectl get roles -A | 모든 네임스페이스 안의 역할 목록 확인하기 |
| kubectl describe role <role-name>-n <namespace-name> | 특정 네임스페이스에 존재하는 특정 롤에 대한 describe 보기 |
| kubectl describe rolebinding <role-name> -n <namespace-name> | 특정 네임스페이스 내의 롤이 할당된 account 보기 |
| kubectl get pods --as <user-name> | 특정 유저의 권한으로 명령어 실행하기(pod 보기) |
| kubectl edit role <role-name> -n <namespace-name> | 특정 네임스페이스 내의 롤에 대한 설정 변경 |
| kubectl get clusterroles --no-headers | wc -l | 클러스터 안에 clusterroles의 개수를 파악 가능, --no-headers | wc -l h : header 빼고 개수 세기 |
| kubectl api-resources --namespaced=false | kubernetes의 api-resource 중 namespace가 따로 없는 api-resource 목록 조회 |
| kubectl describe clusterrolebinding <clusterrole-name> | clusterrole과 바인딩된 유저/ 그룹 조회하기 |
| kubectl get serviceaccounts | service account 목록 보기 |
| kubectl edit <resource> <resource-name> | yaml로 리소스 수정하기(image 변경시에도 사용 가능) |
| kubectl exec <pod-name> -- whoami | 쿠버네티스 클러스터에서 파드에 접속한 뒤, 해당 파드에서 실행 중인 프로세스의 사용자 이름을 확인하는 명령어 |
| kubectl get networkpolicy | Kubernetes 클러스터의 네트워크 정책을 조회하는 명령어 |
| kubectl exec <pod-name> -- cat /path/xxx.log | 파드 내부에서 텍스트 관련 파일 출력(cat) |
| kubectl replace -f xxx.yaml --force | 이름이 겹치는 경우 기존 실행 리소스 지우고 새로운 리소스 강제로 실행 |
| kubectl exec -it hr -- nslookup mysql.payroll > /root/CKA/nslookup.out | hr Pod를 실행할 때 nslookup 명령어로 mysql.payroll에 대한 dns 조회를 함께 실행한다. 그리고 해당 명령어의 출력을 > /root/CKA/nslookup.out에 저장한다. |
| kubectl get all -A | 쿠버네티스 클러스터 내의 모든 네임스페이스에서 실행 중인 모든 주요 리소스를 조회하는 데 사용 -A 옵션은 모든 네임스페이스에 걸쳐 있는 리소스를 나타낸다. |
| kubectl get ingress --all-namespaces | 쿠버네티스 클러스터 내의 모든 네임스페이스에서 인그레스(Ingress) 리소스의 목록을 검색하여 보여주는 명령어 |
| kubelet --version | 쿠블릿 버전 확인 |
| kubectl run redis --image=redis:alpine --labels=tier=db | --labels=tier=db |
| kubectl api-resources -o wide | grep | appVersion 찾기 |
| kubectl expose pod redis --port=6379 --name redis-service | 서비스 노출 |
| kubectl create deployment webapp --image=kodekloud/webapp-color --replicas=3 | dployment는 create |
| kubectl run httpd --image=httpd:alpine --port=80 --expose | 파드를 실행하면서 80번 포트를 노출시키고, --expose로 서비스를 생성한다. 이 옵션은 targetPort를 컨테이너 포트와 같게 설정함(80으로 설정함) |
📌 선언형 접근 정리
apiVersion:
# kubernetes에 오브젝트를 생성할 때 사용하는 apiVersion을 말한다.
# 이 오브젝트를 생성하기 위해 사용하고 있는 쿠버네티스 API 버전이 어떤 것인지를 명시한다.
kind:
# 어떤 종류의 오브젝트를 생성하고자 하는지
# Kind / Version
# Pod / v1
# Service / v1
# Replicaset / apps/v1
# Deployment / apps/v1
metadata:
name : myapp-pod
labels:
app: myapp
type: front-end
# 오브젝트를 유일하게 구분지어 줄 데이터
# name, labels 등 들여쓰기하여 하위 집합으로 표현한다.
# name은 String이고, labels는 dictionary인 key:value로 이어진 쌍이다.
# type으로 pod를 필터링할 수 있다.
spec:
containers:
- name: nginx-container
image: nginx
# 쿠버네티스에 생성할 오브젝트에 대한 정보를 제공한다.
# spec은 dictionary이다.
# container는 List/Array이다.
# 여러 개의 컨테이너가 하나의 pod 안에 있을 수 있기 때문이다.
---
apiVersion: apps/v1 # 오브젝트의 API 버전을 나타soa, 여기서는 apps/v1을 사용
kind: DaemonSet # 오브젝트의 종류, 여기서는 DaemonSet을 사용
metadata: # 오브젝트의 메타데이터를 정의하는 섹션
labels: # 라벨을 정의하는 섹션
app: elasticsearch # 라벨 사용
name: elasticsearch # 오브젝트의 이름을 정의
namespace: kube-system # 오브젝트가 속하는 네임스페이스를 정의
spec: # DaemonSet의 스펙을 정의
selector: # 파드를 선택하는 라벨 셀렉터를 정의
matchLabels: # 라벨 셀렉터의 조건을 지정
app: elasticsearch # app: elasticsearch 라벨을 가진 파드를 선택
template: # 배포할 파드의 템플릿을 정의
metadata: # 파드의 메타데이터를 정의
labels: # 파드의 라벨을 정의
app: elasticsearch # app: elasticsearch 라벨을 사용
spec: # 파드의 스펙을 정의
containers: # 파드 내에서 실행될 컨테이너를 정의
- image: registry.k8s.io/fluentd-elasticsearch:1.20 # 콘테이너의 이미지를 지정
name: fluentd-elasticsearch # 컨테이너의 이름을 정의
apiVersion: v1
kind: Pod
metadata:
name: nginx
spec:
schedulerName: my-scheduler // 커스텀 스케줄러 추가
containers:
- image: nginx
name: nginx
# deployment 기본 모양
apiVersion: apps/v1
kind: Deployment
metadata:
name: frontend
namespace: default
spec:
replicas: 4
selector:
matchLabels:
name: webapp
strategy:
type: Recreate # 배포 전략
template:
metadata:
labels:
name: webapp
spec:
containers:
- image: kodekloud/webapp-color:v2
name: simple-webapp
ports:
- containerPort: 8080
protocol: TCP
apiVersion: v1
kind: Pod
metadata:
name: yellow
spec:
containers:
- name: lemon
image: busybox
command: # 명령어 삽입
- sleep
- "1000"
- name: gold
image: redis
📌 명령형 접근 정리(틀린 문제 위주로)
kubectl run --image=nginx nginx -l tier=frontend
# "nginx"라는 이름의 단일 파드를 생성, "nginx" 컨테이너 이미지를 사용, 라벨 추가
kubectl create deployment --image=nginx nginx
# "nginx"라는 이름의 Kubernetes 배포를 생성(그룹 내 파드)
kubectl expose deployment nginx --port 80
# "nginx" 배포를 80 포트로 노출, 클러스터 내의 다른 파드(pod)가 "nginx" 배포의 파드에 액세스 가능
kubectl edit deployment nginx
# "nginx" 배포를 기본 텍스트 편집기에서 열어 실시간으로 구성을 수정 가능
kubectl scale deployment nginx --replicas=5
# "nginx" 배포를 5개의 복제본으로 확장하며 파드가 항상 5개를 유지하도록 보장
kubectl set image deployment nginx nginx=nginx:1.18
# "nginx" 배포의 컨테이너 이미지를 업데이트
kubectl run redis -l tier=db --image=redis:alpine
# redis 파드 실행, label은 tier=db, 이미지는 redis:alpine 사용
kubectl expose pod redis --port=6379 --name redis-service
# 이미 만들어진 파드 redis에 대한 서비스를 만들어 실행
kubectl create ns dev-ns
#dev-ns라는 namespace 생성
kubectl create deployment redis-deploy --image=redis --replicas=2 -n dev-ns
# redis-deploy 배포 생성, image는 redis, replica 2개, namespace는 dev-ns
kubectl get pods --selector env=dev
# env=dev라는 label을 가지고 있는 파드 가져오기
kubectl get pods --selector env=prod,bu=finance,tier=frontend
# 여러 label을 한 번에 조회
kubectl describe daemonset kube-flannel-ds --all-namespaces
error: a resource cannot be retrieved by name across all namespaces
# describe는 모든 네임스페이스에서 검색 불가능
kubectl describe daemonset kube-flannel-ds --namespace=kube-flannel
# 네임스페이스 조건 추가시 -- 2개임
kubectl get pods -o wide --all-namespaces
# static pods 개수를 확인하기 위해 <pod명>-<node명>의 node 이름을 -o wide로 확인
root@controlplane:~# ps -aux | grep /usr/bin/kubelet
root 3668 0.0 1.5 1933476 63076 ? Ssl Mar13 16:18 /usr/bin/kubelet --bootstrap-kubeconfig=/etc/kubernetes/bootstrap-kubelet.conf --kubeconfig=/etc/kubernetes/kubelet.conf --config=/var/lib/kubelet/config.yaml --network-plugin=cni --pod-infra-container-image=k8s.gcr.io/pause:3.2
root 4879 0.0 0.0 11468 1040 pts/0 S+ 00:06 0:00 grep --color=auto /usr/bin/kubelet
root@controlplane:~# grep -i staticpod /var/lib/kubelet/config.yaml
staticPodPath: /etc/kubernetes/manifests
# static pod definition files 찾기
kubectl run --restart=Never --image=busybox static-busybox --dry-run=client -o yaml --command -- sleep 1000 > /etc/kubernetes/manifests/static-busybox.yaml
# static pod 명령형으로 생성, /etc/kubernetes/manifests/ 이 경로에 생성해야 함
# --restart=Never: 파드를 재시작하지 않도록 설정합니다. 정적 파드는 한 번 생성되면 재시작되지 않습니다.
# --image=busybox:1.28.4: 파드에 사용할 이미지를 지정합니다. 여기서는 버전 1.28.4의 busybox 이미지를 사용합니다.
# static-busybox: 파드의 이름을 지정합니다. 여기서는 "static-busybox"로 지정되었습니다.
# --dry-run=client: 실제로 파드를 생성하지 않고, 클라이언트 측에서만 유효성을 검사하고 생성할 YAML 파일을 출력합니다.
# -o yaml: YAML 형식으로 출력하도록 지정합니다.
# --command -- sleep 1000: 파드가 실행할 명령어를 지정합니다. 여기서는 sleep 명령어를 사용하여 1000초 동안 대기하도록 설정되었습니다.
root@controlplane:~# kubectl get pods --all-namespaces -o wide | grep static-greenbox
default static-greenbox-node01 1/1 Running 0 19s 10.244.1.2 node01 <none> <none>
root@controlplane:~# ssh node01
root@node01:~# ps -ef | grep /usr/bin/kubelet
root 4147 1 0 14:05 ? 00:00:00 /usr/bin/kubelet --bootstrap-kubeconfig=/etc/kubernetes/bootstrap-kubelet.conf
--kubeconfig=/etc/kubernetes/kubelet.conf --config=/var/lib/kubelet/config.yaml --container-runtime-endpoint=unix:///var/run/containerd/containerd.sock --pod-infra-container-image=registry.k8s.io/pause:3.9
root 4773 4733 0 14:05 pts/0 00:00:00 grep /usr/bin/kubelet
root@node01:~# grep -i staticpod /var/lib/kubelet/config.yaml
staticPodPath: /etc/just-to-mess-with-you
root@node01:~# cd /etc/just-to-mess-with-you
root@node01:/etc/just-to-mess-with-you# ls
greenbox.yaml
root@node01:/etc/just-to-mess-with-you# rm -rf greenbox.yaml
# static pod 삭제
pod yaml 파일 작성시 spec.containers.name 필수로 들어가야함
etcd 백업하기
kubectl config get-cluster // 클러스터 이름 확인
kubectl config use-context <cluster-name> // 클러스터 사용
kubectl get node // 변경된 클러스터의 노드 확인
kubectl get pod -n kube-system(네임스페이스) // 해당 파드 찾기
kubectl describe pod <pod-name> -n <namespace> 해당 네임스페이스의 해당 파드의 설명 찾기
// 백업하기
ssh <node-name> // 노드로 접속
// 예시
ETCDCTL_API=3 etcdctl --endpoints=https://10.1.220.8: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/cluster1.db
// 결과 예시 : Snapshot saved at /opt/cluster1.db
// 적용하기
logout
scp <node-name>:/opt/cluster1.db /opt node의 특정 경로의 db 파일을 현재 노드로 이동
Certificate Signing Request 유저 권한 부여
cat akshay.csr | base64 -w 0
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
// kubectl apply -f akshay-csr.yaml
RBAC
특정 역할(권한)을 만들고 특정 유저에게 권한 부여하기
특정 역할 만들기
kubectl create role developer --namespace=default --verb=list,create,delete --resource=pods
특정 유저에게 역할 바인딩하기
kubectl create rolebinding dev-user-binding --namespace=default --role=developer --user=dev-user
특정 클러스터 역할 만들기
kubectl create clusterrole storage-admin --resource=persistentvolumes,storageclasses --verb=get,watch,list,create,delete
특정 유저에게 클러스터 역할 바인딩하기
kubectl create clusterrolebinding michelle-storage-admin --user=michelle --clusterrole=storage-admin
Security Contexts
apiVersion: v1
kind: Pod
metadata:
creationTimestamp: "2024-03-26T15:44:40Z"
name: ubuntu-sleeper
namespace: default
resourceVersion: "782"
uid: be9ddff4-48ef-4ca7-9d0f-ee8f36bd4b66
spec:
securityContext:
runAsUser: 1010 # 특정 유저 실행 권한 부여
containers:
- command:
- sleep
- "4800"
image: ubuntu
imagePullPolicy: Always
name: ubuntu
resources: {}
terminationMessagePath: /dev/termination-log
terminationMessagePolicy: File
securityContext:
capabilities:
add: ["SYS_TIME"] # "SYS_TIME"이라는 시스템 시간을 설정할 권한을 부여
dnsPolicy: ClusterFirst
enableServiceLinks: true
nodeName: controlplane
apiVersion: v1
kind: Pod
metadata:
name: multi-pod
spec:
securityContext:
runAsUser: 1001 # Pod 실행 가능 유저
containers:
- image: ubuntu
name: web
command: ["sleep", "5000"]
securityContext:
runAsUser: 1002 # Container 실행 가능 유저
- image: ubuntu
name: sidecar
command: ["sleep", "5000"]
networkPolicy 정리
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: internal-policy # 네트워크 정책의 이름
namespace: default # 해당 네트워크 정책이 속한 네임스페이스
spec:
podSelector: # 적용 대상 파드 선택
matchLabels:
name: internal # 파드의 레이블 중 name이 internal인 파드에 적용
policyTypes: # 정책 종류 지정 (Egress, Ingress)
- Egress # 외부 트래픽에 대한 정책
- Ingress # 내부 트래픽에 대한 정책
ingress: # Ingress 규칙
- {} # 특정 속성이 없는 경우, 모든 트래픽을 허용
egress: # Egress 규칙
- to: # 목적지 지정
- podSelector: # 파드를 통한 목적지 지정
matchLabels:
name: mysql # 레이블 중 name이 mysql인 파드로의 트래픽 허용
ports: # 포트 지정
- protocol: TCP # 프로토콜 지정
port: 3306 # 포트 번호 지정 (MySQL에 대한 트래픽)
- to: # 목적지 지정
- podSelector: # 파드를 통한 목적지 지정
matchLabels:
name: payroll # 레이블 중 name이 payroll인 파드로의 트래픽 허용
ports: # 포트 지정
- protocol: TCP # 프로토콜 지정
port: 8080 # 포트 번호 지정 (Payroll 애플리케이션에 대한 트래픽)
- ports: # 포트 지정
- port: 53 # 포트 번호 지정
protocol: UDP # 프로토콜 지정
- port: 53 # 포트 번호 지정
protocol: TCP # 프로토콜 지정
pvc
---
kind: PersistentVolumeClaim
apiVersion: v1
metadata:
name: local-pvc
spec:
accessModes:
- ReadWriteOnce
storageClassName: local-storage
resources:
requests:
storage: 500Mi
볼륨 마운트
apiVersion: v1
kind: Pod
metadata:
name: nginx
labels:
name: nginx
spec:
containers:
- name: nginx
image: nginx:alpine
volumeMounts:
- name: local-persistent-storage
mountPath: /var/www/html
volumes:
- name: local-persistent-storage
persistentVolumeClaim:
claimName: local-pvc
StorageClass
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
name: delayed-volume-sc
provisioner: kubernetes.io/no-provisioner
volumeBindingMode: WaitForFirstConsumer
volume 설정
apiVersion: v1
kind: Pod
metadata:
name: webapp
spec:
containers:
- name: event-simulator
image: kodekloud/event-simulator
volumeMounts:
# 볼륨을 마운트할 컨테이너 내의 경로
- mountPath: /log
name: log-volume
volumes:
- name: log-volume
# 파드가 실행되는 노드의 파일 시스템 내의 파일이나 디렉토리를 파드에 마운트할 때 사용
hostPath:
path: /var/log/webapp
pv
apiVersion: v1
kind: PersistentVolume
metadata:
name: pv-log
spec:
# persistentVolumeReclaimPolicy: 볼륨이 사용되지 않게 되었을 때의 처리 정책을 설정
# Retain은 데이터를 보존하며, 수동으로 볼륨을 삭제
persistentVolumeReclaimPolicy: Retain
# accessModes: 볼륨에 접근하는 방식을 설정
ReadWriteMany는 여러 노드에서 동시에 읽기/쓰기가 가능함을 의미
accessModes:
- ReadWriteMany
capacity:
storage: 100Mi
# hostPath: 볼륨이 사용할 호스트 머신의 경로를 설정
hostPath:
path: /pv/log
pvc
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: claim-log-1
spec:
accessModes:
# ReadWriteOnce는 볼륨을 한 번에 하나의 노드에서만 읽고 쓸 수 있음을 의미
- ReadWriteOnce
resources:
# requests: 필요한 최소 리소스 양을 명시합니다. 여기서는 50MiB의 스토리지를 요청
# 이는 PVC가 요청하는 스토리지의 양을 의미하며, 이 요청을 충족하는 PersistentVolume이 할당됨
requests:
storage: 50Mi
특정 노드의 클러스터 연결을 위해 구성된 네트워크 인터페이스를 확인하는 방법
// INTERNAL IP ADDRESS 확인
kubectl get nodes -o wide
// 리눅스 시스템에서 네트워크 인터페이스의 상태를 확인
// ip a | grep xxx.xxx.xxx.xxx
특정 노드의 네트워크 인터페이스를 통해 mac address를 확인하는 방법
ip link show eth0(네트워크 인터페이스)
리눅스 시스템에서 기본 라우팅 테이블을 보여주는 명령어
ip route show default
// 이 명령어를 사용하면 시스템에서 현재 기본 게이트웨이로 라우팅되는 네트워크 트래픽의 경로를 확인할 수 있다.
netstat -nplt
// 리눅스 시스템에서 현재 열려있는 네트워크 포트와 해당 포트를 사용하는 프로세스에 대한 정보를 보여주는 명령어
ps -aux
// 리눅스 시스템에서 현재 실행 중인 프로세스의 상태를 보여주는 데 사용
The CNI binaries의 위치
/opt/cni/bin
ls /etc/cni/net.d/
weave의 ip range
kubectl logs weave-net-4jm4f weave -n kube-system | grep ipalloc-range
서비스의 ip range
cat /etc/kubernetes/manifests/kube-apiserver.yaml | grep cluster-ip-range
ingress controller
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: test-ingress
namespace: critical-space
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /
nginx.ingress.kubernetes.io/ssl-redirect: "false"
spec:
rules:
- http:
paths:
- path: /pay
pathType: Prefix
backend:
service:
name: pay-service
port:
number: 8282
이 구성은 /pay 경로로 들어오는 모든 트래픽을 critical-space 네임스페이스에 있는 pay-service라는 이름을 가진 서비스의 8282번 포트로 라우팅하도록 설정한다.
또한, Nginx Ingress 컨트롤러를 사용하여 경로를 /로 재작성하고 SSL 리다이렉션을 비활성화한다.
참고
뤼튼
UDemy - Certified Kubernetes Administrator (CKA) with Practice Tests
'[DevOps] > Kubernetes' 카테고리의 다른 글
| kubernetes - Label & Selector의 역할 쉽게 이해하기 (1) | 2023.10.26 |
|---|---|
| ReplicationController와 ReplicaSet 간단 정리 (3) | 2023.10.25 |
| kubernetes - Volumes (0) | 2023.07.30 |
| kubernetes - 명령적 접근 방식과 선언적 접근 방식 (2) | 2023.07.19 |
| kubernetes - pod & deployment (0) | 2023.07.17 |