Skip to content
返回部署

Kubernetes RBAC

K8s 基于角色的访问控制 — 角色、绑定和服务账号。

容器高级

为什么

RBAC 限制用户和服务账号在 K8s 的操作。Role 定义权限,RoleBinding 授予主体。默认拒绝 — 显式允许。

何时使用

所有生产集群用 RBAC — 每服务账号最小权限。 简单静态站点跳过容器 — CDN + 静态导出更便宜更快。10 人以下团队避免 Kubernetes;运维开销不合理。

如何做

1. ServiceAccount — pod 身份 2. Role — 命名空间权限 3. ClusterRole — 集群范围权限 4. RoleBinding — 授 Role 给主体 5. ClusterRoleBinding — 授 ClusterRole 6. verbs — get、list、create、update、delete 7. resources — pods、services、deployments

示例

# serviceaccount.yaml apiVersion: v1 kind: ServiceAccount metadata: { name: myapp } # role.yaml — 只读 apiVersion: rbac.authorization.k8s.io/v1 kind: Role metadata: { name: reader } rules: - apiGroups: [""] resources: ["pods", "services"] verbs: ["get", "list", "watch"] # rolebinding.yaml apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding metadata: { name: reader-binding } subjects: - kind: ServiceAccount name: myapp roleRef: { kind: Role, name: reader, apiGroup: rbac.authorization.k8s.io } # pod 中使用 spec: serviceAccountName: myapp

常见问题

  • ⚠Forbidden 错误 — 服务账号缺权限,查 RoleBinding
  • ⚠过宽 — 用 cluster-admin,建特定 Role 最小权限
  • ⚠环境间配置漂移 — 使用基础设施即代码(Terraform/Pulumi)保持 dev/staging/prod 一致

最佳实践

  • ✓最小权限 — 仅授所需 verbs,应用永不 cluster-admin
  • ✓pod 用 ServiceAccount — 非默认,配特定最小 Role
  • ✓设置健康检查和优雅关闭 — 处理 SIGTERM 以在退出前排空进行中的请求

常见问题解答