命名空间的出现,原理上是为了划分组的方式来管理pod在哪个namespace上运行,而不需要去关心这些pod具体在哪个节点上工作,就好像QQ群一样。
查看ns
[root@master ~]# kubectl get ns
NAME STATUS AGE
default Active 166m
kube-node-lease Active 166m
kube-public Active 166m
kube-system Active 166m
新建一个ns
[root@master ~]# kubectl create ns ns1
namespace/ns1 created
[root@master ~]# kubectl get ns
NAME STATUS AGE
default Active 166m
kube-node-lease Active 166m
kube-public Active 166m
kube-system Active 166m
ns1 Active 1s
删除一个命名空间
[root@master ~]# kubectl delete ns ns1
namespace "ns1" deleted
如果删不掉ns1就需要特别处理
kubectl delete ns ns1 #先用delete删除
kubectl proxy --port=8081 #单独开一个终端,做api代理
#下面通过强制删除ns1
kubectl get ns ns1 -o json | jq 'del(.spec.finalizers)' |curl -v -H "Content-Type: application/json" -X PUT --data-binary @- http://127.0.0.1:8081/api/v1/namespaces/ns1/finalize
[root@master ~]#kubectl get ns
NAME STATUS AGE
default Active 3h24m
kube-node-lease Active 3h24m
kube-public Active 3h24m
kube-system Active 3h24m
#这样就删除干净了
没有jq的话,可以按照如下方式安装jq
wget http://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
rpm -ivh epel-release-latest-7.noarch.rpm
yum repolist
yum install -y jq
namespace快速切换器kubectx的安装
git clone https://github.com/ahmetb/kubectx.git
cp kubectx/kube* /usr/local/bin/ ##把相关文件放到可执行目录里
[root@master kubectx-master]# kubens
default
kube-node-lease
kube-public
kube-system
ns1
[root@master kubectx-master]# kubens --help
USAGE:
kubens : list the namespaces in the current context #list namespace
kubens <NAME> : change the active namespace of current context #切换namespace
kubens - : switch to the previous namespace in this context #切到原来的
kubens -c, --current : show the current namespace #显示当前namespace
kubens -h,--help : show this message
[root@master kubectx-master]# kubens ns1
Context "kubernetes-admin@kubernetes" modified.
Active namespace is "ns1".
[root@master kubectx-master]# kubens
default
kube-node-lease
kube-public
kube-system
ns1
[root@master kubectx-master]# kubens -c
ns1
[root@master kubectx-master]# kubectl config set-context --current --namespace=ns1 #还可以原生的切换
Context "kubernetes-admin@kubernetes" modified.
[root@master kubectx-master]# kubens - #查看之前的namespace
Context "kubernetes-admin@kubernetes" modified.
Active namespace is "ns1".
[root@master kubectx-master]# kubens -
Context "kubernetes-admin@kubernetes" modified.
Active namespace is "ns1".
[root@master kubectx-master]# kubens -c #查看当前的namespace
ns1
[root@master kubectx-master]# kubectl get pods #查当前的namespace下有什么资源
No resources found in ns1 namespace.
[root@master kubectx-master]# kubens #查看所有的namespace
default
kube-node-lease
kube-public
kube-system
ns1
[root@master kubectx-master]# kubens default #切换回default
Context "kubernetes-admin@kubernetes" modified.
Active namespace is "default".
[root@master kubectx-master]# kubectl get pods #查当前的namespace下有什么资源,发现有了原来的资源了
NAME READY STATUS RESTARTS AGE
nginx-deployment-c7c9d97b4-7vdrh 1/1 Running 0 103m
nginx-deployment-c7c9d97b4-gcn4f 1/1 Running 0 78m