
가상적인 쿠버네티스 클러스터 분리 기능
완전한 분리 개념이 아니기 때문에 용도는 제한되지만, 하나의 쿠버네티스 클러스터를 여러팀에서 사용하거나 서비스 환경/스테이징 환경/개발 환경으로 구분하는 경우 사용 가능
기본 설정에서 제공하는 Namespace
kube-systemkube-publickube-node-leasedefault관리형 서비스나 구축 도구로 구축된 경우 대부분의 쿠버네티스 클러스터는 RBAC이 기본값으로 활성화되어 있으며 일부 환경에서는 네트워크 정책을 사용할 수 있음
RBAC은 클러스터 조작에 대한 권한을 네임스페이스별로 구분할 수 있고 네트워크 정책과 함께 사용하여 네임스페이스 간의 통신을 제어할 수 있는 구조
네임스페이스만으로는 높은 분리성을 확보하기 어렵지만 RBAC 이나 네트워크 정책을 사용하면 분리성을 높일 수 있음

kubeconfig(기본 위치는 ~/.kube/config)에 쓰여 있는 정보를 사용하여 접속apiVersion: v1
kind: Config
preferences: {}
clusters: # 1. 클러스터 목록 시작
- name: sample-cluster # 리스트 아이템(-) 뒤에 한 칸 공백
cluster: # name과 같은 레벨
server: https://localhost:6443 # 부모(cluster)보다 2칸 더 들여쓰기
users: # 2. 유저 정보 시작
- name: sample-user
user:
client-certificate-data: LS0tLs1CRUd3Ti...
client-key-data: l_S0tl_S1CRUdJTi...
contexts: # 3. 컨텍스트(조합) 시작
- name: sample-context
context:
cluster: sample-cluster
namespace: default
user: sample-user
current-context: sample-context # 현재 활성화된 컨텍스트 이름
cluster/users/contexts 세 가지cluster 에는 접속 대상 클러스터 정보를 정의users 에는 인증 정보를 정의X.509 클라이언트 인증서/토큰/패스워드/웹훅 등 다양한 방식을 사용할 수 있음contexts 에는 cluster 와 user 그리고 네임스페이스를 지정한 것을 정의# 클러스터(prd-cluster) 정의를 추가, 변경
kubectl config set-cluster prd-cluster --server=https://localhost:6443
# 인증 정보 정의를 추가, 변경
kubectl config set-credentials admin-user --client-certificate=./sample.crt --
client-key=./sample.key --embed-certs=true
# 컨텍스트 정의(클러스터/인증 정보/네임스페이스 정의)를 추가 및 변경
kubectl config set-context prd-admin --cluster=prd-cluster --user=admin-user
--namespace=default
# 현재 컨텍스트 확인
kubectl config current-context
# 명령어를 실행할 때 컨텍스트 지정
kubectl get pods --context
kubectl runkubectl run nginx --image=nginx
# 확인
kubectl get pods
kubectl create deployment 디플로이먼트이름 --image=이미지이름kubectl create deployment dpy-nginx --image=nginx
# 확인
kubectl get pods
kubectl createkubectl create -f 리소스파일경로# 리소스 파일 작성(sample-pod.yaml)
apiVersion: v1
kind: Pod
metadata:
name: sample-pod
spec:
containers:
- name: nginx-container
image: nginx:1.16
# 리소스 생성
kubectl create -f sample-pod.yaml
# 존재하지 않는 경우
pod/sample-pod created
# 존재하는 경우
Error from server (AlreadyExists): error when creating "sample-pod.yaml": pods
"sample-pod" already exists
kubectl deletekubectl delete -f 리소스파일kubectl delete -f sample-pod.yaml
# 리소스가 존재하는 경우
pod "sample-pod" deleted
# 리소스가 존재하지 않는 경우
Error from server (NotFound): error when deleting "sample-pod.yaml": pods
"sample-pod" not found
리소스 종류와 이름을 이용하여 삭제
kubectl delete 리소스종류 [리소스이름]--all 을 사용하면 모든 리소스 삭제kubectl 명령어 실행은 바로 완료되지만 쿠버네티스에 의한 실제 리소스 처리는 비동기로 실행되어 처리가 바로 완료되지 않음
--wait 옵션을 사용하면 리소스의 삭제 완료를 기다렸다가 명령어 실행을 종료할 수 있는데 모든 Finalizer(삭제 표시된 리소스를 완전히 삭제하기 전에 특정 조건이 충족될 때까지 기다리도록 쿠버네티스에 지시하는 네임스페이스 키) 실행이 완료될 때까지 대기
리소스를 강제로 즉시 삭제하려면 정지까지 유예 기간을 0으로 하는 --grace-period -0 옵션과 강제로 삭제하는 --force 옵션을 사용
--force 옵션 지정만으로 --grace-period 0 옵션도 자동으로 부여비슷한 옵션으로 --now 가 있지만 이 옵션은 --grace-period 1 과 동일하여 바로 삭제가 안 되는 경우가 있으니 주의
리소스 삭제: 삭제 완료 대기
kubectl delete -f sample-pod.yaml --wait리소스 삭제: 즉시 강제 삭제
kubectl delete -f sample-pod.yaml --grace-period 0 --forcekubectl apply# 없으면 생성
kubectl apply -f sample-pod.yaml
# >> pod/sample-pod created
# 변경 내용이 없으면 적용하지 않음
kubectl apply -f sample-pod.yaml
# >> pod/sample-pod unchanged
kubectl get pods 명령어에 옵션을 사용하여 확인할 수 있음kubectl get pods -ㅐ jsonpath='{.items[*].spec.containers[*].image}'kubectl apply 로 적용된 변경 사항은 이전에 적용한 매니페스트, 현재 클러스터에 등록된 리소스 상태, 이번에 적용할 매니페스트, 이렇게 세 종류에서 산출현재 리소스 상태와 이번에 적용할 매니페스트를 비교하여 산출이전에 적용한 매니페스트와 이번에 적용할 매니페스트를 기준으로 산출--save-config 옵션 없이 kubectl create를 사용하여 리소스를 생성한 경우에는 이전 상태가 저장되지 않기 때문에 이번에 적용할 매니페스트에서 특정 필드를 삭제하고 싶은 경우에 변경 사항을 산출하지 못하고 의도한 대로 반영되지 않는 필드가 생성될 수 있음Warning: kubectl apply should be used on resource created by either
kubectl create --save-config or kubectl apply pod/sample-pod configured
Client-side apply) 여러 사용자나 구성 요소가 동시에 같은 필드를 변경하는 경우 경합 현상이 발생할 수 있는데 이 문제를 해결하기 위해 필드를 변경한 구성 요소(kubectl 이나 구성 요소의 이름)를 기록하는 기능과 서버 측에서 변경 사항을 계산하는 기능이 도입됨kubectl set image 명령어에서는 매니페스트 파일을 사용하지 않고 서버 측 정보를 직접 수정하여 컨테이너 이미지를 변경할 수 있는데 이 명령어는 매니페스트를 수정하지 않기 때문에 kubectl apply 명령어로 매니페스트를 다시 적용하면 컨테이너 이미지가 원래대로 돌아가버리는 예상치 못한 변경이 발생--server-side 옵션을 사용# sample-pod.yaml 파일 수정
apiVersion: v1
kind: Pod
metadata:
name: sample-pod
spec:
containers:
- name: nginx-container
image: nginx:1.16
# 리소스 배포
kubectl apply -f sample-pod.yaml
# >> pod/sample-pod created
# 이미지 확인
kubectl get pods -o jsonpath='{.items[*].spec.containers[*].image}'
# >> nginx:1.16
# 이미지 수정
kubectl set image pod sample-pod nginx-container=nginx:1.17
# >> pod/sample-pod image updated
# 이미지 확인
kubectl get pods -o jsonpath='{.items[*].spec.containers[*].image}'
# >> nginx:1.17
# 리소스 배포
kubectl apply -f sample-pod.yaml
# pod/sample-pod created
# 이미지 확인
kubectl get pods -o jsonpath='{.items[*].spec.containers[*].image}'
# >> nginx:1.16
📌 명령형(Imperative) vs 선언적(Declarative)
kubectl set image(명령형 방식)
- 클러스터의 실행 중인 객체(Live Object)는 즉시 변경되지만, 로컬에 있는 YAML 파일은 수정되지 않음
kubectl apply -f(선언적 방식)
- 쿠버네티스는 파일의 내용과 현재 실행 중인 상태(1.17)를 비교하고, 파일에 적힌대로 다시 1.16으로 되돌려버림.
# 모든 파드 삭제
kubectl delete pod --all
# 리소스 배포
kubectl apply -f sample-pod.yaml --server-side
# 이미지 확인
kubectl get pods -o jsonpath='{.items[*].spec.containers[*].image}'
# 이미지 수정
kubectl set image pod sample-pod nginx-container=nginx:1.17
# 이미지 확인
kubectl get pods -o jsonpath='{.items[*].spec.containers[*].image}'
# 리소스 배포
kubectl apply -f sample-pod.yaml
# >> error: Apply failed with 1 conflict: conflict with "kubectl-set" using v1:
# >> .spec.containers[name="nginx-container"].image
# >> Please review the fields above--they currently have other managers. Here
# >> are the ways you can resolve this warning:
# 충돌을 무시하고 적용
kubectl apply -f sample-pod.yaml --server-side --force-conflicts
# >> pod/sample-pod serverside-applied
-rollout restart# sample-deployment.yaml 파일을 생성하고 작성
apiVersion: apps/v1
kind: Deployment
metadata:
name: sample-deployment
spec:
replicas: 3
selector:
matchLabels:
app: sample-app
template:
metadata:
labels:
app: sample-app
spec:
containers:
- name: nginx-container
image: nginx
# 리소스 생성
kubectl apply -f sample-pod.yaml
# >> pod/sample-pod created
kubectl apply -f sample-deployment.yaml
# >> deployment.apps/sample-deployment created
# 파드 재시작
kubectl rollout restart deployment sample-deployment
# >> deployment.apps/sample-deployment restarted
kubectl rollout restart pod sample-pod
# >> error: pods "sample-pod" restarting is not supported
metadata.name 대신 metadata.generateName 을 지정하고 리소스를 생성하면 그 이름에 접두사(prefix)를 붙여 이름이 자동으로 생성# sample-generatename.yaml 파일을 생성하고 작성
apiVersion: v1
kind: Pod
metadata:
generateName: sample-generatename
spec:
containers:
- name: nginx-container
image: nginx
# 리소스 생성
kubectl create -f sample-generatename.yaml
# >> pod/sample-generatename-mdlxg created
kubectl create -f sample-generatename.yaml
# >> pod/sample-generatename-7gtmr created
kubectl create -f sample-generatename.yaml
# >> pod/sample-generatename-bjwv9 created
# 리소스 확인
kubectl get pods
# 모든 리소스 삭제
kubectl delete all --all
kubectl get all
# >> No resources found in default namespace.
kubectl wait 명령어인데, 실행하면 --for 옵션에 지정한 상태가 되기까지 kubectl 명령어가 최대 --timeout 옵션에 지정하는 시간(기본값은 30초)까지 종료하지 않고 대기# 파드 3개 생성
kubectl create -f sample-pod.yaml
# >> pod/sample-pod created
kubectl create -f sample-generatename.yaml
# >> pod/sample-generatename-h6qpz created
kubectl create -f sample-generatename.yaml
# >> pod/sample-generatename-kppck created
# sample-pod 가 정상적으로 기동할 때(Ready 상태가 될 때)까지 대기
kubectl wait --for=condition=Ready pod/sample-pod
# >> pod/sample-pod condition met
# 모든 파드가 삭제될 때까지 파드마다 5초씩 대기하는데 아직 파드를 삭제하지 않았으므로 타임아웃
kubectl wait --for=delete pod --all --timeout=5s
# >> timed out waiting for the condition on pods/sample-generatename-h6qpz
# >> client rate limiter Wait returned an error: context deadline exceeded
# >> client rate limiter Wait returned an error: context deadline exceeded
# 모든 파드를 삭제한 후 곧바로 kubectl wait를 실행
kubectl delete pod --all --wait=false
# >> pod "sample-generatename-h6qpz" deleted
# >> pod "sample-generatename-kppck" deleted
# >> pod "sample-pod" deleted
# 모든 파드가 삭제될 때까지 대기
kubectl wait --for=delete pod --all
# 리소스에 매니패스트 파일 사용 가능
kubectl apply -f sample-pod.yaml
# >> pod/sample-pod created
kubectl wait --for=condition=Ready -f sample-pod.yaml
# >> pod/sample-pod condition met
# 매니페스트 적용
kubectl apply -f sample-multi-resource-manifest.yaml
# >> deployment.apps/order1-deployment created
# >> service/order2-service created
kubectl apply -f ./ -R 과 같이 -R 옵션을 사용하면 재귀적으로 디렉터리 안에 존재하는 매니페스트 파일을 적용할 수도 있음Label : 리소스를 분류/검색하는 태그Annotation : 추가적인 긴 설명/메타데이터 저장소| 구분 | Label | Annotation |
|---|---|---|
| 주요 목적 | 리소스 분류, 선택, 검색에 사용 | 리소스에 추가 설명/메타데이터 |
| 저장(Storage) | etcd (인덱싱됨) | etcd (비인덱싱됨) |
| 검색/Selector 지원 | 지원 (Label Selector로 매칭) | 지원 안 함 (Selector 불가) |
| Key 형식 | prefix/name (DNS prefix 허용) | 동일 |
| Key 길이 제한 | 253자 이하 | 253자 이하 |
| Value 길이 제한 | 63자 이하 | 262,144자(256KB) 이하 |
| Value 용도 | 간단한 구분자 | 설명, 설정, 빌드 정보 등 |
metadata.annotations 로 설정할 수 있는 메타데이터# sample-annotations.yaml 파일 생성 및 작성
apiVersion: v1
kind: Pod
metadata:
name: sample-annotations
annotations:
annotation1: val1
annotation2: "200"
spec:
containers:
- name: nginx-container
image: nginx:1.16
# 리소스 생성
kubectl apply -f sample-annotations.yaml
# >> pod/sample-annotations created
# 리소스 생성 후 어노테이션 부여
kubectl annotate pods sample-annotations annotations3=val3
# >> pod/sample-annotations annotated
# 어노테이션 덮어쓰기
kubectl annotate pods sample-annotations annotations3=val3-new --overwrite
# >> pod/sample-annotations annotated
# 어노테이션 확인
kubectl describe pod sample-annotations
# 어노테이션 삭제
kubectl annotate pods sample-annotations annotations3-
apiVersion: v1
kind: Pod
metadata:
name: sample-label
labels:
label1: val1
label2: val2
spec:
containers:
- name: nginx-container
image: nginx:1.16
# 리소스 생성
kubectl apply -f sample-label.yaml
# >> pod/sample-label created
# 리소스 생성 후 부여
kubectl label pods sample-label label3=val3
# >> pod/sample-label labeled
# 어노테이션 덮어쓰기
kubectl label pods sample-label label3=val3-new --overwrite
# >> pod/sample-label labeled
# 레이블 확인
kubectl describe pod sample-label
# 레이블 삭제
kubectl label pods sample-label label3-
# >> pod/sample-label labeled
# label1=val1 과 label2 레이블을 가진 파드를 표시
kubectl get pods -l label1=val1,label2
# 모든 레이블을 표시하고 파드 목록을 출력
kubectl get pods --show-labels
시스템이 사용하는 레이블
권장되는 레이블 키 이름: 쿠버네티스의 에코시스템을 구성하는 OSS에서도 사용
app.kubernetes.io/name: 애플리케이션 이름app.kubernetes.io/version: 애플리케이션 버전app.kubernetes.io/component: 애플리케이션 내 구성 요소app.kubernetes.io/part-of: 애플리케이션이 전체적으로 구성하는 시스템 이름app.kubernetes.io/instance: 애플리케이션이나 시스템을 식별하는 인스턴스명app.kubernetes.io/managed-by: 이 애플리케이션을 관리하는 데 사용되는 도구--prune 옵션kubectl apply --prune 명령어를 계속 실행하는 것만으로 매니페스트에서 삭제된 리소스도 자동으로 삭제할 수 있음# 리소스 생성
kubectl apply -f ./prune
# >> pod/sample-pod1 created
# >> pod/sample-pod2 created
# sample-pod2.yaml 파일을 삭제
# 리소스 수정
kubectl apply -f ./prune
# >> pod/sample-pod1 unchanged
# 리소스 확인
kubectl get pods
kubectl set 변경할정보 리소스종류 리소스이름 실제값# 파드 생성
kubectl apply -f sample-pod.yaml
# >> pod/sample-pod created
# 파드의 이미지 변경
kubectl set image pod sample-pod nginx-container=1.17
# >> pod/sample-pod image updated
# diff 명령 이용해서 확인
kubectl diff -f sample-pod.yaml
# 모든 리소스 종류 표시
kubectl api-resources
# 네임스페이스 수준의 리소스
kubectl api-resources --namespaced=true
# 클러스터 수준의 리소스
kubectl api-resources --namespaced=false
# 리소스 전체 가져오기
kubectl get all
# 리소스를 지정해서 목록에 해당하는 리소스 전체 가져오기(여러 개를 가져오고자 하는 경우는 리소스 종류 나열)
kubectl get 리소스종류
# 리소스 중 특정한 이름을 가진 리소스 정보 가져오기
kubectl get 리소스종류 리소스이름
# 특정 레이블을 가진 리소스 가져오기
kubectl get 리소스종류 label이름=레이블값
# 노드 목록 표시
kubectl get nodes
—-output(-o) 옵션을 사용# 자세히 표시
kubectl get pods -o wide
# yaml로 표시
kubectl get pods -o yaml
kubectl get pods -o yaml sample-pod
# Custom-columns 사용해서 컬럼 이름 수정
kubectl get pods -o custom-columns="NAME:{.metadata.name},NodeIP:{.status.hostIP}"
# JSON Path 형식의 출력은 특정 항목을 표시하며 셸 스크립트 등으로
# 변수에 특정 값을 지정하는 등 특정 값을 조사할 때 자주 사용
kubectl get pods sample-pod -o jsonpath="{.metadata.name}"
# YAML 적용
kubectl apply -f https://github.com/kubernetes-sigs/metricsserver/releases/latest/download/components.yaml
# Metrics Server Pod 확인
kubectl -n kube-system get pods | grep metrics-server
# 로컬 쿠버네티스인 경우는 매니페스트 수정
kubectl edit deploy metrics-server -n kube-system
# 아래 내용 추가
containers:
- name: metrics-server
image: k8s.gcr.io/metrics-server/metrics-server:v0.7.1
args:
- --kubelet-insecure-tls
- --kubelet-preferred-address-types=InternalIP,ExternalIP,Hostname
# 적용
kubectl rollout restart deploy metrics-server -n kube-system
# 노드의 리소스 사용량 확인
kubectl top node
# 파드의 리소스 사용량 확인
kubectl -n kube-system top pod
# 컨테이너의 리소스 사용량 확인
kubectl -n kube-system top pod --containers
kubectl apply -f sample-pod.yaml
kubectl exec -it sample-pod -- /bin/ls
# >> bin docker-entrypoint.d home mnt root srv usr
# >> boot docker-entrypoint.sh lib opt run sys var
# >> dev etc media proc sbin tmp
kubectl exec -it sample-pod -c nginx-container -- /bin/ls
# >> bin docker-entrypoint.d home mnt root srv usr
# >> boot docker-entrypoint.sh lib opt run sys var
# >> dev etc media proc sbin tmp
# bash 셸에 접속
kubectl exec -it sample-pod -- /bin/bash
# 인수를 전달해서 실행
kubectl exec -it sample-pod -- /bin/bash -c "ls -all --classify | grep lib"
# >> lrwxrwxrwx 1 root root 7 Dec 2 00:00 lib -> usr/lib/
kubectl logs 파드이름kubectl logs 파드이름 -c 컨테이너이름-f 옵션kubectl logs --since=1h --tail=10 --timestamps=true 파드이름kubectl logs --selector 테이블kubectl cp 소스 타겟kubectl apply -f sample-pod.yaml
# >> pod/sample-pod created
kubectl cp sample-pod:etc/hostname ./hostname
cat hostname
# >> sample-pod
kubectl cp hostname sample-pod:/tmp/newfile
kubectl exec -it sample-pod -- ls /tmp
# >> newfile


localhost 로 통신할 수 있음

# sample-pod.yaml 파일 생성 및 작성
apiVersion: v1
kind: Pod
metadata:
name: sample-pod
spec:
containers:
- name: nginx-container
image: nginx
# 리소스 파일 적용
kubectl apply -f sample-pod.yaml
# >> pod/sample-pod created

# 정상적으로 생성되었는지 확인
kubectl get pods
# 추가적인 정보를 얻으려면 -o wide 옵션 사용
kubectl get deployment -o wide
# sample-2pod.yaml 파일을 생성하고 작성
apiVersion: v1
kind: Pod
metadata:
name: sample-2pod
spec:
containers:
- name: nginx-container
image: nginx:1.16
- name: redis-container
image: redis:3.2
# 파드 생성
kubectl apply -f sample-2pod.yaml
# 파드 확인
kubectl get pods
# sample-2pod-fail.yaml 파일을 생성하고 작성
apiVersion: v1
kind: Pod
metadata:
name: sample-2pod-fail
spec:
containers:
- name: nginx-container-112
image: nginx:1.16
- name: nginx-container-113
image: nginx:1.17
# 파드 생성
kubectl apply -f sample-2pod-fail.yaml
# 파드 확인 - 동일한 포트를 사용하므로 첫번째만 컨테이너로 기동되고
# 두번째 컨테이너는 기동 안 됨
kubectl get pods
# 로그 확인
kubectl logs sample-2pod-fail -c nginx-container-113