Kubernetes 之 Namespace
Namespace 的定义
Kubernetes 可以构建多个逻辑域进行隔离,它们底层依赖于同一个物理集群, 这些虚拟域被称为命名空间。命名空间 Namespace 是 k8s 顶层级别的资源,可以给不同的管理员、租户、项目环境或项目创建对应的命名空间,例如,可以为 test、development、production 环境分别创建各自的命名空间。
Namespace 空间的使用方式
# 创建 test 命名空间
root@k8s-master1:~# kubectl create ns test
namespace/test created
# 查看命名空间内的 pods
root@k8s-master1:~# kubectl get pods -n test
No resources found in test namespace.
# 删除命名空间
root@k8s-master1:~# kubectl delete ns/test
namespace "test" deleted
Namespace 分配资源限额
-
编写
ns-test-quota.yaml
文件apiVersion: v1 kind: ResourceQuota metadata: name: cpu-memory-quota namespace: test spec: hard: requests.cpu: "2" # Pod 请求的 CPU 限制 requests.memory: 2Gi # Pod 请求的内存限制 limits.cpu: "4" # 空间最多使用的 CPU 限制 limits.memory: 4Gi # 空间最多使用的内存限制
-
执行并查看限额情况
# 创建空间限额 root@k8s-master1:~# kubectl apply -f ns-test-quota.yaml resourcequota/cpu-memory-quota created # 查看限额情况 root@k8s-master1:~# kubectl get resourcequota -n test NAME AGE REQUEST LIMIT cpu-memory-quota 103s requests.cpu: 0/2, requests.memory: 0/2Gi limits.cpu: 0/4, limits.memory: 0/4Gi
-
测试空间限额
-
制作
k8s-test:v1.0
镜像,Dockerfile
、nginx.conf
和index.html
如下所示:FROM alpine:latest RUN apk update && apk add nginx curl stress-ng && mkdir "/usr/share/nginx/html" COPY index.html /usr/share/nginx/html/index.html COPY nginx.conf /etc/nginx/nginx.conf EXPOSE 80 CMD ["nginx", "-g", "daemon off;"]
worker_processes 1; events { worker_connections 1024; } http { include /etc/nginx/mime.types; default_type application/octet-stream; server { listen 80; server_name localhost; location / { root /usr/share/nginx/html; index index.html index.htm; } } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Nginx Test</title> </head> <body> Hello World </body> </html>
-
先编写超过空间限额的 Pod
exceed-ns.yaml
文件测试apiVersion: v1 kind: Pod metadata: name: pod-exceed-test namespace: test labels: app: pod-exceed-test spec: containers: - name: pod-exceed-test ports: - containerPort: 80 image: k8s-test:v1.0 imagePullPolicy: IfNotPresent resources: requests: memory: "4Gi" cpu: "4" limits: memory: "8Gi" cpu: "8"
root@k8s-master1:~# kubectl apply -f exceed-ns.yaml Error from server (Forbidden): error when creating "exceed-ns.yaml": pods "pod-exceed-test" is forbidden: exceeded quota: cpu-memory-quota, requested: limits.cpu=8,limits.memory=8Gi,requests.cpu=4,requests.memory=4Gi, used: limits.cpu=0,limits.memory=0,requests.cpu=0,requests.memory=0, limited: limits.cpu=4,limits.memory=4Gi,requests.cpu=2,requests.memory=2Gi
-
修改为合适的资源进行压测(请求为 1 核心 1GiB 内存,上限为 2 核心 2 GiB 内存)
root@k8s-master1:~# kubectl exec pod/pod-exceed-test -n test -- stress-ng --cpu 1 --vm 1 --vm-bytes 1G --timeout 10m stress-ng: info: [8] setting to a 10 mins, 0 secs run per stressor stress-ng: info: [8] dispatching hogs: 1 cpu, 1 vm root@k8s-master1:~# kubectl get resourcequota -n test NAME AGE REQUEST LIMIT cpu-memory-quota 23m requests.cpu: 1/2, requests.memory: 1Gi/2Gi limits.cpu: 2/4, limits.memory: 2Gi/4Gi
-