k8s命名空间为对象名称提供了一个作用域,我们可以把资源放到不同的命名空间中,这样我们可以使用同名的资源名称,只要保证同一命名空间中的资源名称唯一即可
# kubectl get ns
NAME STATUS AGE
default Active 19d
kube-node-lease Active 19d
kube-public Active 19d
kube-system Active 19d
# kubectl get pod --namespace kube-system
NAME READY STATUS RESTARTS AGE
calico-kube-controllers-65b8787765-rbk76 1/1 Running 6 19d
calico-node-g6pl7 1/1 Running 6 19d
calico-node-lk8r7 1/1 Running 5 19d
calico-node-mp27p 1/1 Running 5 19d
coredns-5c468949c8-5cmnv 1/1 Running 6 19d
coredns-5c468949c8-mc99b 1/1 Running 6 19d
etcd-master 1/1 Running 7 19d
kube-apiserver-master 1/1 Running 7 19d
kube-controller-manager-master 1/1 Running 9 19d
kube-proxy-dbfdb 1/1 Running 5 19d
kube-proxy-lvww9 1/1 Running 6 19d
kube-proxy-qg6pc 1/1 Running 5 19d
kube-scheduler-master 1/1 Running 9 19d
通过yml文件创建命名空间
# cat test-namespace.yml
apiVersion: v1
kind: Namespace
metadata:
name: test-namespace
查看创建好的命名空间
# kubectl get ns
NAME STATUS AGE
default Active 19d
kube-node-lease Active 19d
kube-public Active 19d
kube-system Active 19d
test-namespace Active 10s
也可以通过命令行形式创建命名空间
# kubectl create namespace cmd-namespace
namespace/cmd-namespace created
查看通过命令行创建的命名空间
# kubectl get ns
NAME STATUS AGE
cmd-namespace Active 4s
default Active 19d
kube-node-lease Active 19d
kube-public Active 19d
kube-system Active 19d
test-namespace Active 100s
指定命名空间创建pod
# cat nginx-namespace.yml
apiVersion: v1
kind: Pod
metadata:
name: nginx-ns
namespace: test-namespace
spec:
nodeSelector:
server: 'backend'
containers:
- image: nginx:latest
name: nginx-ns
ports:
- containerPort: 80
protocol: TCP
启动pod kubectl create -f nginx-namespace.yml
查看pod
# kubectl get pod -n test-namespace
NAME READY STATUS RESTARTS AGE
nginx-ns 1/1 Running 0 6m7s
创建一个同名的资源对象在不同的namespace中
# kubectl create namespace test-namespace-2
namespace/test-namespace-2 created
创建同名pod
# cat nginx-namespace-2.yml
apiVersion: v1
kind: Pod
metadata:
name: nginx-ns
namespace: test-namespace-2
spec:
nodeSelector:
server: 'backend'
containers:
- image: nginx:latest
name: nginx-ns
ports:
- containerPort: 80
protocol: TCP
启动pod kubectl create -f nginx-namespace-2.yml
查看pod
# kubectl get pod -n test-namespace-2
NAME READY STATUS RESTARTS AGE
nginx-ns 1/1 Running 0 105s
当我们想删除pod时,需要指定对应的命名空间,不指定则为默认的default命名空间,如果想删除当前命名空间中的所有pod,则只需要执行
kubectl delete ns test-namespace
即删除整个命名空间,pod将会伴随命名空间自动删除