Kubernetes namespace
Namespace
namespace는 k8s 자원에 대한 영역으로 클러스터 하나를 여러 개의 논리적인 단위로 나눠서 사용하며, 권한과 정책을 cluster의 하위 section에 적용하는 메커니즘 제공한다. 즉, 자원을 그룹화해 관리할 수 있는 기회 제공한다.
namespace 사용
namespace는 용도에 따라 실행해야 하는 앱을 구분할 때 사용한다.
정리하자면 아래와 같다.
- 클러스터 하나를 여러 팀이나 사용자가 함께 공유 영역 구분
- 개발 환경, 테스트 환경, 운영 환경 같은 소프트웨어 환경 구분
- 인프라팀이 볼 수 있는 구역과 개발팀이 볼 수 있는 구역 구분
- 권한의 boundary
- 자원의 boundary
 
네임스테이스 사용하기
- 
namespace 생성 - CLI
kubectl create namespace blue kubectl get namespaces
- yaml
kubectl create namespace green --dry-run=client -o yaml > green-ns.yaml kubectl create -f greem-ns.yaml
 
- CLI
- 
namespace 관리 kubectl get namespaces kubectl delete namespace
namespaces 조회
등록된 namespaces 조회는 아래와 같다.
kubectl get namespace
처음 설치하고 바로 namespaces 목록을 조회해 보면 아래와 같다.
% kubectl get namespaces
NAME              STATUS   AGE
default           Active   5m30s
kube-node-lease   Active   5m31s
kube-public       Active   5m31s
kube-system       Active   5m31s
기본으로 네이스페이스는 4개가 존재한다.
Cluster 생성 시 다음의 기본적인 namespace 사용
default
- 다른 namespace가 없는 object를 위한 기본 namespace
- container, pod, service, replicaset 등의 자원에 대한 영역을 제공
kube-system
- kubernetes system에서 생성한 object를 위한 namespace
kube-public
- 자동으로 생성되며 모든 사용자 (인증되지 않은 사용자 포함)가 읽기 권한으로 접근할 수 있다
- 주로 전체 cluster 중에 공개적으로 드러나서 읽을 수 있는 resource를 위해 예약되어 있다
- 공개적인 성격은 단지 관례이지 요구사항은 아니다!
default namespace
아무 것도 없는 상태에서 Pod를 조회해 보자.
% kubectl get pod
No resources found in default namespace.
위 내용을 보면 default namespace에 없다는 것으로 보와, namespace를 지정하지 않으면 default를 기본으로 사용하고 있다는 것을 알 수 있다.
아래 명령는 다 동일한 동작을 한다.
kubectl get pod
kubectl get pod --namespace default
kubectl get pod -n default
특정 namespace에서 Pod 조회
kubectl get pods -n [조회할 네이스테이스명]
아래 명령을 kube-system namespace에 있는 Pod를 조회한 것이다.
% kubectl get pods -n kube-system
NAME                               READY   STATUS    RESTARTS        AGE
coredns-6d4b75cb6d-7shzf           1/1     Running   0               6m13s
etcd-minikube                      1/1     Running   0               6m28s
kube-apiserver-minikube            1/1     Running   0               6m26s
kube-controller-manager-minikube   1/1     Running   0               6m26s
kube-proxy-dbd6p                   1/1     Running   0               6m13s
kube-scheduler-minikube            1/1     Running   0               6m26s
모든 namespace에서 Pod 조회
모든 namespace에서 Pod 조회 명령은 아래와 같다.
kubectl get pods --all-namespaces
실제 실행해 보자.
% kubectl get pods --all-namespaces
NAMESPACE     NAME                               READY   STATUS    RESTARTS      AGE
kube-system   coredns-6d4b75cb6d-7shzf           1/1     Running   0             10m
kube-system   etcd-minikube                      1/1     Running   0             11m
kube-system   kube-apiserver-minikube            1/1     Running   0             11m
kube-system   kube-controller-manager-minikube   1/1     Running   0             11m
kube-system   kube-proxy-dbd6p                   1/1     Running   0             10m
kube-system   kube-scheduler-minikube            1/1     Running   0             11m
kube-system   storage-provisioner                1/1     Running   1 (10m ago)   11m
여기에서는 kube-system 밖에 없는데, 이는 따로 Pod를 생성하지 않았기 때문이다.
namespace 생성하기
CLI로 namespace 생성하기
-CLI에서 namespace를 생성하는 명령은 아래와 같다.
kubectl create namespace [생성할 네이스페이스명]
실제 blue라는 네이스페이스를 생성해 보자.
% kubectl create namespace blue
namespace/blue created
생성되었는지 확인 한다.
% kubectl get namespaces
NAME              STATUS   AGE
blue              Active   10s <<<<<<<< 생성된 blue namespace
default           Active   27m
kube-node-lease   Active   27m
kube-public       Active   27m
kube-system       Active   27m
yaml로 namespace 생성하기
yaml로 namespace를 생성해 보자.
kubectl create namespace [생성할 네이스페이스명] --dry-run=client -o yaml
% kubectl create namespace green --dry-run=client -o yaml
apiVersion: v1
kind: Namespace
metadata:
  creationTimestamp: null
  name: green
spec: {}
status: {}
green-ns.yaml 파일로 생성한다.
$ kubectl create namespace green --dry-run -o yaml > green-ns.yaml
green-ns.yaml를 필요한 것만 남겨 두기 위해 아래와 같이 수정한다.
apiVersion: v1
kind: Namespace
metadata:
  name: green
생성한 green-ns.yaml로 namespace를 만든다.
% kubectl create -f green-ns.yaml
namespace/green created
생성되었는지 확인 한다.
% kubectl get namespaces
NAME              STATUS   AGE
blue              Active   11m
default           Active   27m
green             Active   43s <<<<<<<< 생성된 green namespace
kube-node-lease   Active   27m
kube-public       Active   27m
kube-system       Active   27m
특정 namespace에 Pod 생성하기
특정 namespace에 CLI에서 Pod 생성하기
아래 명령어로 namespace 플래그(--namespace)를 green으로 지정해서 Pod를 생성한다.
% kubectl run nginx --image=nginx:1.14 --port 80 --namespace green
pod/nginx created
green namespace에 있는 Pod를 조회해 보면, 정상적으로 생성된 것을 볼 수 있다.
% kubectl get pods -n green
NAME        READY   STATUS    RESTARTS   AGE
webserver   1/1     Running   0          48s
특정 namespace 삭제
grean namespace에 생성한 Pod를 삭제한다.
% kubectl delete pod nginx -n green
pod "nginx" deleted
주의할 점 : namespace를 삭제하면 안에 들어가 있던 Pod도 모두 삭제 된다.
특정 namespace에 yaml에서 Pod 생성하기
nginx.yaml 파일을 생성한다.
$ kubectl run nginx --image=nginx:1.14 --port 80 --dry-run=client -o yaml > nginx.yaml
생성된 nginx.yaml 파일을 아래와 같이 수정한다.
apiVersion: v1
kind: Pod
metadata:
  labels:
    run: nginx
  name: nginx
spec:
  containers:
  - image: nginx:1.14
    name: nginx
    ports:
    - containerPort: 80
이번에는 namespace 플래그를 지정하여 생성해 본다.
kubectl create -f nginx.yaml -n green
특정 namespace에 yaml에 namespace 지정하여 Pod 생성하기
nginx.yaml 파일에서 metadata>namespace 아래와 같이 green을 지정한다.
apiVersion: v1
kind: Pod
metadata:
  labels:
    run: nginx
  name: nginx
  namespace: green # namespace 지정
spec:
  containers:
  - image: nginx:1.14
    name: nginx
    ports:
    - containerPort: 80
이번에는 namespace 플래그(-n green) 지정 없이 생성해 본다. (기존에 동일한 Pod명이 있다면 삭제를 먼저 진행해야 한다.)
% kubectl create -f nginx.yaml
pod/nginx created
green namespace에 있는 Pod를 조회해 보면, 정상적으로 생성된 것을 볼 수 있다.
% kubectl get pods -n green
NAME    READY   STATUS    RESTARTS   AGE
nginx   1/1     Running   0          17s
사용할 네임스테이스 switch - kubectl config
기본으로 사용하는 namespace를 defalut가 아닌 이름의 namespace로 switch
사용 방법: namespace를 포함한 context 등록
$ kubectl config --help
$ kubectl config set-context NAME --cluster=kubernetes ...
$ kubectl config view
등록된 namespace로 context 변경
$ kubectl config use-context NAME
config 도움말 보기
kubectl config --help
실행 결과:
% kubectl config --help
Modify kubeconfig files using subcommands like "kubectl config set current-context my-context"
 The loading order follows these rules:
  1.  If the --kubeconfig flag is set, then only that file is loaded. The flag may only be set once and no merging takes
place.
  2.  If $KUBECONFIG environment variable is set, then it is used as a list of paths (normal path delimiting rules for
your system). These paths are merged. When a value is modified, it is modified in the file that defines the stanza. When
a value is created, it is created in the first file that exists. If no files in the chain exist, then it creates the
last file in the list.
  3.  Otherwise, ${HOME}/.kube/config is used and no merging takes place.
Available Commands:
  current-context   Display the current-context
  delete-cluster    kubeconfig에서 지정된 클러스터를 삭제합니다
  delete-context    kubeconfig에서 지정된 컨텍스트를 삭제합니다
  delete-user       Delete the specified user from the kubeconfig
  get-clusters      kubeconfig에 정의된 클러스터를 표시합니다
  get-contexts      하나 또는 여러 컨텍스트를 설명합니다
  get-users         Display users defined in the kubeconfig
  rename-context    Rename a context from the kubeconfig file
  set               Set an individual value in a kubeconfig file
  set-cluster       Set a cluster entry in kubeconfig
  set-context       Set a context entry in kubeconfig
  set-credentials   Set a user entry in kubeconfig
  unset             Unset an individual value in a kubeconfig file
  use-context       Set the current-context in a kubeconfig file
  view              병합된 kubeconfig 설정 또는 지정된 kubeconfig 파일을 표시합니다
Usage:
  kubectl config SUBCOMMAND [options]
Use "kubectl <command> --help" for more information about a given command.
Use "kubectl options" for a list of global command-line options (applies to all commands).
config 설정 내용 보기
kubectl config view
실행 결과:
% kubectl config view
apiVersion: v1
clusters:
- cluster:
... 중간 생략 ...
contexts:
- context:
    cluster: minikube
    extensions:
    - extension:
        last-update: Sat, 10 Sep 2022 09:22:47 KST
        provider: minikube.sigs.k8s.io
        version: v1.26.1
      name: context_info
    namespace: default
    user: minikube
  name: minikube
current-context: minikube
... 마지막 생략 ...
신규 컨테스트 추가
kubectl config use-context green@kubenetes --cluster=minikube --user=kubernates-admin --namespace=green
현재 컨테스트 확인
% kubectl config current-context
minikube
현재 컨테스트 변경
kubectl config use-context [컨텍스트명]