Namespace
概述
Namespace(命名空间)是Kubernetes中实现多租户资源隔离的核心机制。通过命名空间,可以在同一个物理集群中创建多个虚拟集群,实现资源、权限和网络的隔离。
核心概念
命名空间的作用
- 资源隔离:不同命名空间的资源相互隔离
- 权限控制:基于命名空间的RBAC权限管理
- 资源配额:为不同命名空间设置资源限制
- 网络策略:控制命名空间间的网络访问
默认命名空间
- default:默认命名空间,未指定命名空间的资源都在这里
- kube-system:Kubernetes系统组件所在的命名空间
- kube-public:公共资源,所有用户可读
- kube-node-lease:节点心跳数据,用于节点健康检测
命名空间管理
创建命名空间
yaml
# 方式1:YAML文件创建
apiVersion: v1
kind: Namespace
metadata:
name: development
labels:
name: development
environment: dev
annotations:
description: "Development environment namespace"
---
# 方式2:命令行创建
# kubectl create namespace development
# 方式3:带标签创建
# kubectl create namespace development --dry-run=client -o yaml | \
# kubectl label --local -f - environment=dev -o yaml | kubectl apply -f -命名空间配置
yaml
apiVersion: v1
kind: Namespace
metadata:
name: production
labels:
name: production
environment: prod
team: platform
annotations:
description: "Production environment namespace"
owner: "platform-team@company.com"
created-by: "admin"
created-date: "2024-01-15"
spec:
finalizers:
- kubernetes命名空间操作
bash
# 查看所有命名空间
kubectl get namespaces
kubectl get ns
# 查看命名空间详情
kubectl describe namespace development
kubectl get namespace development -o yaml
# 查看命名空间资源使用
kubectl top pods -n development
kubectl get all -n development
# 删除命名空间
kubectl delete namespace development
# 编辑命名空间
kubectl edit namespace development
# 设置默认命名空间
kubectl config set-context --current --namespace=development
# 查看当前命名空间
kubectl config view --minify | grep namespace资源隔离
资源类型分类
yaml
# 命名空间级别资源(Namespaced Resources)
- Pods
- Services
- Deployments
- ConfigMaps
- Secrets
- ResourceQuotas
- LimitRanges
- PersistentVolumeClaims
- Ingresses
- NetworkPolicies
# 集群级别资源(Cluster-scoped Resources)
- Nodes
- PersistentVolumes
- ClusterRoles
- ClusterRoleBindings
- Namespaces
- StorageClasses
- CustomResourceDefinitions跨命名空间访问
yaml
# Service跨命名空间访问
# 格式:<service-name>.<namespace>.svc.cluster.local
apiVersion: v1
kind: Pod
metadata:
name: client-pod
namespace: development
spec:
containers:
- name: client
image: busybox
command: ["sh", "-c", "wget http://api-service.production.svc.cluster.local:8080/api"]
---
# 在development命名空间访问production命名空间的服务
# 完整域名:api-service.production.svc.cluster.local
# 简写:api-service.production命名空间配额
yaml
apiVersion: v1
kind: ResourceQuota
metadata:
name: compute-quota
namespace: development
spec:
hard:
requests.cpu: "4"
requests.memory: "8Gi"
limits.cpu: "8"
limits.memory: "16Gi"
pods: "20"
persistentvolumeclaims: "10"
services: "10"
secrets: "20"
configmaps: "20"
---
apiVersion: v1
kind: ResourceQuota
metadata:
name: object-count-quota
namespace: development
spec:
hard:
count/deployments.apps: "10"
count/statefulsets.apps: "5"
count/jobs.batch: "20"
count/cronjobs.batch: "10"配额限制
LimitRange配置
yaml
apiVersion: v1
kind: LimitRange
metadata:
name: default-limits
namespace: development
spec:
limits:
- type: Container
default:
cpu: "500m"
memory: "512Mi"
defaultRequest:
cpu: "100m"
memory: "128Mi"
max:
cpu: "2"
memory: "2Gi"
min:
cpu: "50m"
memory: "64Mi"
- type: PersistentVolumeClaim
max:
storage: "50Gi"
min:
storage: "1Gi"ResourceQuota详细配置
yaml
apiVersion: v1
kind: ResourceQuota
metadata:
name: comprehensive-quota
namespace: production
spec:
hard:
# 计算资源
requests.cpu: "20"
requests.memory: "40Gi"
limits.cpu: "40"
limits.memory: "80Gi"
# 存储资源
persistentvolumeclaims: "20"
requests.storage: "200Gi"
# 对象数量
pods: "100"
services: "20"
secrets: "50"
configmaps: "50"
replicationcontrollers: "10"
# 特定资源类型
count/deployments.apps: "20"
count/statefulsets.apps: "10"
count/daemonsets.apps: "5"
count/jobs.batch: "50"
count/cronjobs.batch: "20"
count/ingresses.networking.k8s.io: "10"配额作用域
yaml
apiVersion: v1
kind: ResourceQuota
metadata:
name: terminating-pods-quota
namespace: development
spec:
hard:
pods: "10"
cpu: "2"
memory: "4Gi"
scopes:
- Terminating
---
apiVersion: v1
kind: ResourceQuota
metadata:
name: not-terminating-pods-quota
namespace: development
spec:
hard:
pods: "20"
cpu: "5"
memory: "10Gi"
scopes:
- NotTerminating
---
apiVersion: v1
kind: ResourceQuota
metadata:
name: besteffort-pods-quota
namespace: development
spec:
hard:
pods: "5"
scopes:
- BestEffort实用kubectl操作命令
命名空间管理命令
bash
# 创建命名空间
kubectl create namespace <name>
kubectl apply -f namespace.yaml
# 查看命名空间
kubectl get namespaces
kubectl get ns -o wide
kubectl get ns -o yaml
kubectl get ns -o json
# 查看命名空间详情
kubectl describe namespace <name>
# 删除命名空间
kubectl delete namespace <name>
kubectl delete -f namespace.yaml
# 编辑命名空间
kubectl edit namespace <name>
# 标签管理
kubectl label namespace <name> key=value
kubectl label namespace <name> key-
kubectl get ns --show-labels
# 注解管理
kubectl annotate namespace <name> key=value
kubectl annotate namespace <name> key-资源操作命令
bash
# 在特定命名空间操作
kubectl get pods -n <namespace>
kubectl get all -n <namespace>
kubectl describe pod <pod-name> -n <namespace>
# 设置默认命名空间
kubectl config set-context --current --namespace=<namespace>
# 查看所有命名空间的资源
kubectl get pods --all-namespaces
kubectl get pods -A
# 按标签过滤命名空间
kubectl get ns -l environment=production
# 查看命名空间资源使用
kubectl top pods -n <namespace>
kubectl top pods --all-namespaces
# 查看命名空间资源配额
kubectl get resourcequota -n <namespace>
kubectl describe resourcequota -n <namespace>
# 查看命名空间限制范围
kubectl get limitrange -n <namespace>
kubectl describe limitrange -n <namespace>高级操作命令
bash
# 查看命名空间事件
kubectl get events -n <namespace> --sort-by='.lastTimestamp'
# 查看命名空间资源统计
kubectl api-resources --namespaced=true
# 导出命名空间资源
kubectl get all -n <namespace> -o yaml > namespace-backup.yaml
# 批量操作多个命名空间
for ns in dev staging prod; do
echo "Namespace: $ns"
kubectl get pods -n $ns
done
# 查看命名空间资源限制
kubectl get pods -n <namespace> -o custom-columns=\
'NAME:.metadata.name,\
MEM_REQ:.spec.containers[0].resources.requests.memory,\
MEM_LIM:.spec.containers[0].resources.limits.memory,\
CPU_REQ:.spec.containers[0].resources.requests.cpu,\
CPU_LIM:.spec.containers[0].resources.limits.cpu'
# 检查命名空间资源配额使用情况
kubectl get resourcequota -n <namespace> -o json | \
jq '.items[] | {name: .metadata.name, hard: .spec.hard, used: .status.used}'实践示例
示例1:多环境命名空间隔离
yaml
# 开发环境
apiVersion: v1
kind: Namespace
metadata:
name: development
labels:
name: development
environment: dev
annotations:
description: "Development environment"
owner: "dev-team@company.com"
---
apiVersion: v1
kind: ResourceQuota
metadata:
name: dev-quota
namespace: development
spec:
hard:
requests.cpu: "4"
requests.memory: "8Gi"
limits.cpu: "8"
limits.memory: "16Gi"
pods: "20"
services: "10"
persistentvolumeclaims: "10"
---
apiVersion: v1
kind: LimitRange
metadata:
name: dev-limits
namespace: development
spec:
limits:
- type: Container
default:
cpu: "500m"
memory: "512Mi"
defaultRequest:
cpu: "100m"
memory: "128Mi"
max:
cpu: "2"
memory: "2Gi"
---
# 测试环境
apiVersion: v1
kind: Namespace
metadata:
name: staging
labels:
name: staging
environment: staging
annotations:
description: "Staging environment"
owner: "qa-team@company.com"
---
apiVersion: v1
kind: ResourceQuota
metadata:
name: staging-quota
namespace: staging
spec:
hard:
requests.cpu: "8"
requests.memory: "16Gi"
limits.cpu: "16"
limits.memory: "32Gi"
pods: "50"
services: "20"
persistentvolumeclaims: "20"
---
# 生产环境
apiVersion: v1
kind: Namespace
metadata:
name: production
labels:
name: production
environment: prod
annotations:
description: "Production environment"
owner: "ops-team@company.com"
---
apiVersion: v1
kind: ResourceQuota
metadata:
name: prod-quota
namespace: production
spec:
hard:
requests.cpu: "20"
requests.memory: "40Gi"
limits.cpu: "40"
limits.memory: "80Gi"
pods: "100"
services: "30"
persistentvolumeclaims: "30"
---
apiVersion: v1
kind: LimitRange
metadata:
name: prod-limits
namespace: production
spec:
limits:
- type: Container
default:
cpu: "1"
memory: "1Gi"
defaultRequest:
cpu: "500m"
memory: "512Mi"
max:
cpu: "4"
memory: "8Gi"应用场景:为开发、测试、生产环境创建独立的命名空间,实现环境隔离和资源控制。
示例2:多租户命名空间管理
yaml
# 租户A命名空间
apiVersion: v1
kind: Namespace
metadata:
name: tenant-a
labels:
name: tenant-a
tenant: a
tier: gold
annotations:
owner: "tenant-a@company.com"
billing-code: "TENANT-A-001"
---
apiVersion: v1
kind: ResourceQuota
metadata:
name: tenant-a-quota
namespace: tenant-a
spec:
hard:
requests.cpu: "10"
requests.memory: "20Gi"
limits.cpu: "20"
limits.memory: "40Gi"
pods: "50"
services: "20"
persistentvolumeclaims: "20"
requests.storage: "100Gi"
---
# 租户B命名空间
apiVersion: v1
kind: Namespace
metadata:
name: tenant-b
labels:
name: tenant-b
tenant: b
tier: silver
annotations:
owner: "tenant-b@company.com"
billing-code: "TENANT-B-002"
---
apiVersion: v1
kind: ResourceQuota
metadata:
name: tenant-b-quota
namespace: tenant-b
spec:
hard:
requests.cpu: "5"
requests.memory: "10Gi"
limits.cpu: "10"
limits.memory: "20Gi"
pods: "30"
services: "10"
persistentvolumeclaims: "10"
requests.storage: "50Gi"
---
# 租户C命名空间
apiVersion: v1
kind: Namespace
metadata:
name: tenant-c
labels:
name: tenant-c
tenant: c
tier: bronze
annotations:
owner: "tenant-c@company.com"
billing-code: "TENANT-C-003"
---
apiVersion: v1
kind: ResourceQuota
metadata:
name: tenant-c-quota
namespace: tenant-c
spec:
hard:
requests.cpu: "2"
requests.memory: "4Gi"
limits.cpu: "4"
limits.memory: "8Gi"
pods: "10"
services: "5"
persistentvolumeclaims: "5"
requests.storage: "20Gi"
---
# 网络策略:限制租户间访问
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: tenant-a-isolation
namespace: tenant-a
spec:
podSelector: {}
policyTypes:
- Ingress
- Egress
ingress:
- from:
- namespaceSelector:
matchLabels:
tenant: a
egress:
- to:
- namespaceSelector:
matchLabels:
tenant: a应用场景:为不同租户创建独立的命名空间,实现资源隔离、配额管理和网络隔离。
示例3:项目级命名空间管理
yaml
# 项目A命名空间
apiVersion: v1
kind: Namespace
metadata:
name: project-a
labels:
name: project-a
project: a
cost-center: "CC-001"
annotations:
description: "Project A namespace"
owner: "project-a-team@company.com"
budget: "10000"
created-date: "2024-01-01"
---
apiVersion: v1
kind: ResourceQuota
metadata:
name: project-a-quota
namespace: project-a
spec:
hard:
requests.cpu: "8"
requests.memory: "16Gi"
limits.cpu: "16"
limits.memory: "32Gi"
pods: "30"
services: "15"
persistentvolumeclaims: "15"
requests.storage: "100Gi"
count/deployments.apps: "10"
count/statefulsets.apps: "5"
---
apiVersion: v1
kind: LimitRange
metadata:
name: project-a-limits
namespace: project-a
spec:
limits:
- type: Container
default:
cpu: "500m"
memory: "512Mi"
defaultRequest:
cpu: "200m"
memory: "256Mi"
max:
cpu: "2"
memory: "4Gi"
min:
cpu: "50m"
memory: "64Mi"
---
# 项目A的应用
apiVersion: apps/v1
kind: Deployment
metadata:
name: webapp
namespace: project-a
spec:
replicas: 3
selector:
matchLabels:
app: webapp
template:
metadata:
labels:
app: webapp
spec:
containers:
- name: webapp
image: nginx:1.20
resources:
requests:
cpu: "200m"
memory: "256Mi"
limits:
cpu: "500m"
memory: "512Mi"
---
apiVersion: v1
kind: Service
metadata:
name: webapp-service
namespace: project-a
spec:
selector:
app: webapp
ports:
- port: 80
targetPort: 80
---
# 项目A的配置
apiVersion: v1
kind: ConfigMap
metadata:
name: webapp-config
namespace: project-a
data:
APP_ENV: "production"
DB_HOST: "mysql.project-a.svc.cluster.local"
---
apiVersion: v1
kind: Secret
metadata:
name: webapp-secret
namespace: project-a
type: Opaque
stringData:
DB_PASSWORD: "password123"应用场景:为项目创建独立的命名空间,包含完整的应用栈和配置管理。
故障排查指南
常见问题诊断
1. 命名空间无法删除(Terminating状态)
bash
# 查看命名空间状态
kubectl get namespace <name>
# 常见输出
NAME STATUS AGE
test-ns Terminating 10m
# 查看命名空间详情
kubectl describe namespace <name>
# 查看finalizers
kubectl get namespace <name> -o yaml
# 解决方案1:删除finalizers
kubectl edit namespace <name>
# 删除spec.finalizers字段
# 解决方案2:强制删除
kubectl delete namespace <name> --force --grace-period=0
# 解决方案3:清理资源
# 查看命名空间中的所有资源
kubectl get all -n <name>
kubectl get pvc -n <name>
kubectl get configmap -n <name>
kubectl get secret -n <name>
# 删除所有资源
kubectl delete all --all -n <name>
kubectl delete pvc --all -n <name>2. 资源配额超限
bash
# 查看资源配额状态
kubectl describe resourcequota -n <namespace>
# 常见错误信息
Error from server (Forbidden): error when creating "deployment.yaml": deployments.apps is forbidden: exceeded quota: compute-quota, requested: requests.cpu=500m, used: requests.cpu=4, limited: requests.cpu=4
# 排查步骤
# 1. 查看当前资源使用
kubectl top pods -n <namespace>
kubectl get pods -n <namespace> -o custom-columns=\
'NAME:.metadata.name,\
CPU_REQ:.spec.containers[0].resources.requests.cpu,\
MEM_REQ:.spec.containers[0].resources.requests.memory'
# 2. 查看资源配额
kubectl get resourcequota -n <namespace> -o yaml
# 解决方案
# - 删除不必要的资源
# - 调整资源配额
# - 优化资源配置3. 跨命名空间访问失败
bash
# 查看Service
kubectl get svc -n <namespace>
# 查看网络策略
kubectl get networkpolicy -n <namespace>
# 测试跨命名空间访问
kubectl run test --image=busybox -n <namespace> --rm -it --restart=Never -- \
wget -qO- http://service-name.target-namespace.svc.cluster.local:port
# 检查DNS解析
kubectl run test --image=busybox -n <namespace> --rm -it --restart=Never -- \
nslookup service-name.target-namespace.svc.cluster.local
# 解决方案
# - 检查Service名称和命名空间
# - 检查网络策略是否阻止访问
# - 检查DNS配置4. 命名空间资源泄漏
bash
# 查看命名空间资源统计
kubectl get all -n <namespace>
kubectl get pvc -n <namespace>
kubectl get configmap -n <namespace>
kubectl get secret -n <namespace>
# 查看资源使用情况
kubectl top pods -n <namespace>
# 清理未使用的资源
# 删除未使用的ConfigMap
kubectl get configmap -n <namespace> -o json | \
jq -r '.items[] | select(.metadata.annotations."kubectl.kubernetes.io/last-applied-configuration" == null) | .metadata.name' | \
xargs kubectl delete configmap -n <namespace>
# 删除未使用的Secret
kubectl get secret -n <namespace> -o json | \
jq -r '.items[] | select(.type == "Opaque" and .metadata.annotations."kubectl.kubernetes.io/last-applied-configuration" == null) | .metadata.name' | \
xargs kubectl delete secret -n <namespace>命名空间监控脚本
bash
#!/bin/bash
# 命名空间监控脚本
echo "=== 命名空间概览 ==="
kubectl get namespaces
echo -e "\n=== 命名空间资源统计 ==="
for ns in $(kubectl get namespaces -o jsonpath='{.items[*].metadata.name}'); do
echo "Namespace: $ns"
echo " Pods: $(kubectl get pods -n $ns --no-headers | wc -l)"
echo " Services: $(kubectl get svc -n $ns --no-headers | wc -l)"
echo " Deployments: $(kubectl get deploy -n $ns --no-headers 2>/dev/null | wc -l)"
echo " PVCs: $(kubectl get pvc -n $ns --no-headers 2>/dev/null | wc -l)"
echo ""
done
echo "=== 命名空间资源配额使用 ==="
for ns in $(kubectl get namespaces -o jsonpath='{.items[*].metadata.name}'); do
quota=$(kubectl get resourcequota -n $ns -o name 2>/dev/null)
if [ -n "$quota" ]; then
echo "Namespace: $ns"
kubectl describe resourcequota -n $ns | grep -A 20 "Used\|Hard"
echo ""
fi
done
echo "=== 命名空间资源使用率 ==="
kubectl top pods --all-namespaces | head -20最佳实践建议
1. 命名空间命名规范
yaml
# 推荐的命名规范
# 环境命名空间
- development / dev
- staging / test
- production / prod
# 项目命名空间
- project-<name>
- team-<name>
- app-<name>
# 租户命名空间
- tenant-<id>
- customer-<name>
# 示例
metadata:
name: project-webapp-prod
labels:
project: webapp
environment: production
team: platform2. 命名空间标签规范
yaml
apiVersion: v1
kind: Namespace
metadata:
name: production
labels:
# 基本标签
name: production
environment: production
# 组织标签
team: platform
department: engineering
cost-center: "CC-001"
# 分级标签
tier: "1"
criticality: high
# 管理标签
managed-by: kubectl
created-by: admin3. 命名空间注解规范
yaml
apiVersion: v1
kind: Namespace
metadata:
name: production
annotations:
# 描述信息
description: "Production environment namespace"
# 负责人信息
owner: "platform-team@company.com"
contact: "ops-team@company.com"
# 业务信息
billing-code: "PROD-001"
budget: "50000"
# 管理信息
created-by: "admin"
created-date: "2024-01-15"
last-updated: "2024-01-20"
# 文档链接
documentation: "https://wiki.company.com/namespaces/production"
runbook: "https://runbook.company.com/production"4. 命名空间资源规划
yaml
# 小型项目(开发环境)
apiVersion: v1
kind: ResourceQuota
metadata:
name: small-project-quota
namespace: project-small
spec:
hard:
requests.cpu: "2"
requests.memory: "4Gi"
limits.cpu: "4"
limits.memory: "8Gi"
pods: "10"
services: "5"
persistentvolumeclaims: "5"
---
# 中型项目(测试环境)
apiVersion: v1
kind: ResourceQuota
metadata:
name: medium-project-quota
namespace: project-medium
spec:
hard:
requests.cpu: "8"
requests.memory: "16Gi"
limits.cpu: "16"
limits.memory: "32Gi"
pods: "50"
services: "20"
persistentvolumeclaims: "20"
---
# 大型项目(生产环境)
apiVersion: v1
kind: ResourceQuota
metadata:
name: large-project-quota
namespace: project-large
spec:
hard:
requests.cpu: "20"
requests.memory: "40Gi"
limits.cpu: "40"
limits.memory: "80Gi"
pods: "100"
services: "30"
persistentvolumeclaims: "30"5. 命名空间安全最佳实践
yaml
# 1. 使用RBAC限制命名空间访问
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: namespace-admin
namespace: development
rules:
- apiGroups: [""]
resources: ["*"]
verbs: ["*"]
- apiGroups: ["apps"]
resources: ["*"]
verbs: ["*"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: dev-team-admin
namespace: development
subjects:
- kind: User
name: dev-user
apiGroup: rbac.authorization.k8s.io
roleRef:
kind: Role
name: namespace-admin
apiGroup: rbac.authorization.k8s.io
---
# 2. 使用NetworkPolicy限制网络访问
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: deny-all-ingress
namespace: production
spec:
podSelector: {}
policyTypes:
- Ingress
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-same-namespace
namespace: production
spec:
podSelector: {}
policyTypes:
- Ingress
ingress:
- from:
- podSelector: {}6. 命名空间管理清单
markdown
## 命名空间管理检查清单
### 创建命名空间
- [ ] 设置合适的命名空间名称
- [ ] 添加必要的标签和注解
- [ ] 配置资源配额(ResourceQuota)
- [ ] 配置默认资源限制(LimitRange)
- [ ] 设置RBAC权限
- [ ] 配置网络策略(可选)
### 管理命名空间
- [ ] 定期监控资源使用情况
- [ ] 清理未使用的资源
- [ ] 审查资源配额使用情况
- [ ] 更新标签和注解
- [ ] 备份重要配置
### 删除命名空间
- [ ] 确认命名空间中的资源
- [ ] 备份重要数据
- [ ] 删除所有资源
- [ ] 删除命名空间
- [ ] 验证删除成功总结
核心要点
命名空间基础
- 实现资源的逻辑隔离
- 支持多租户和多环境
- 提供资源配额和权限控制
资源隔离
- 命名空间级别资源相互隔离
- 跨命名空间访问使用完整域名
- 通过网络策略控制访问
配额管理
- ResourceQuota限制命名空间总资源
- LimitRange设置默认资源限制
- 按需分配资源配额
最佳实践
- 使用规范的命名和标签
- 合理规划资源配额
- 实施安全隔离策略
常用命令速查
bash
# 命名空间管理
kubectl get namespaces
kubectl create namespace <name>
kubectl delete namespace <name>
# 资源操作
kubectl get pods -n <namespace>
kubectl get all -n <namespace>
kubectl apply -f resource.yaml -n <namespace>
# 配额管理
kubectl get resourcequota -n <namespace>
kubectl describe resourcequota -n <namespace>
# 设置默认命名空间
kubectl config set-context --current --namespace=<namespace>
# 查看所有命名空间资源
kubectl get pods --all-namespaces