E-NO
Kubernetes Namespace security 7 Min Read

Kubernetes Namespace Security Hardening with Practical Examples

calendar_today Published: 2026-09-30
update Last Updated: 2026-10-01
analytics SEO Efficiency: 100%
Technical guide illustration for Kubernetes Namespace Security Hardening with Practical Examples.

Intro

Kubernetes namespaces are not security boundaries by themselves. They are organizational units that let you group resources, but securing them requires deliberate configuration of Role-Based Access Control (RBAC), resource quotas, network policies, pod security standards, and secrets management. Without hardening, a compromised container in one namespace can read secrets, exhaust cluster capacity, or reach services in other namespaces.

This article gives you a practical walkthrough for hardening Kubernetes namespace security. It is aimed at developers, DevOps consultants, and startup platform teams. You will learn how to observe current state, apply minimal changes, and verify that each change achieves its intended effect. Every section includes concrete kubectl commands, manifests, expected output, and recovery steps.

A note on operational safety: Before making any change, capture the current state and timestamps. Protect credentials and private material. Change one scoped item at a time, and only when you understand its blast radius and recovery path. Use placeholders instead of real secrets in commands you share or log.

Version and Environment Inventory

Before you harden anything, know exactly what you are running. Start with a read-only inventory of your cluster and namespace. This establishes a baseline for troubleshooting and change verification.

Check cluster and client versions

kubectl version --short

Expected output includes both client and server versions. The server version is the Kubernetes control plane; the client is your kubectl binary. Keep them within one or two minor versions of each other to avoid API compatibility surprises. For example:

Client Version: v1.28.3
Kustomize Version: v5.0.4-0.20230601165947-6ce0bf390ce3
Server Version: v1.28.2

Inspect the target namespace

kubectl get namespace production -o yaml

The output shows labels, annotations, and the namespace status. This is the raw configuration you will be modifying.

List all resources in the namespace

kubectl get all -n production

This shows pods, services, deployments, replicasets, and statefulsets. A wide view helps you understand what is running and who might be affected by changes:

kubectl get pods -n production -o wide

Check pod details, events, and logs:

kubectl describe pod <pod-name> -n production
kubectl logs <pod-name> -n production --previous
kubectl rollout status deployment/<deployment-name> -n production

These commands reveal scheduling issues, crash loops, and deployment failures. Do not assume a release succeeded just because apply returned no error.

Check RBAC bindings relevant to the namespace

kubectl get rolebindings,clusterrolebindings -n production

This shows who can act inside the namespace and whether any cluster-wide bindings grant broad permissions.

Record your baseline

Save the output of these commands to a timestamped directory. For example:

mkdir -p baseline/$(date +%Y%m%d-%H%M%S)
kubectl get namespace production -o yaml > baseline/$(date +%Y%m%d-%H%M%S)/namespace.yaml
kubectl get all -n production -o yaml > baseline/$(date +%Y%m%d-%H%M%S)/all-resources.yaml
kubectl get rolebindings,clusterrolebindings -n production -o yaml > baseline/$(date +%Y%m%d-%H%M%S)/rbac.yaml

Now you can compare before and after states, and you have a recovery point.

Quick check 1 of 2

What does the 'namespace' field in a Kubernetes object's metadata represent?

The passage states that namespace defines the space within which each name must be unique, and an empty namespace is equivalent to the 'default' namespace.

Safe Configuration Path

Hardening should follow a sequence that minimizes risk: first understand the current configuration, then make one change, then verify, then move to the next. In this section you will harden a namespace's access control, resource limits, and pod security settings.

1. Isolate the Namespace

Namespaces alone do not isolate network traffic. But you can use labels and resource structure to make intent explicit. For a production namespace, consider a label like purpose=production, team=backend. This helps with policy targeting later.

kubectl label namespace production purpose=production team=backend

2. Harden RBAC

RBAC is the primary mechanism for controlling access to Kubernetes API. The principle of least privilege: grant only the permissions a user or service account needs, and no more.

Create a Role with minimal permissions

Save the following as backend-role.yaml:

apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  namespace: production
  name: backend-deployer
rules:
- apiGroups: [""]
  resources: ["pods", "services", "configmaps", "secrets"]
  verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]
- apiGroups: ["apps"]
  resources: ["deployments", "replicasets"]
  verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]

This role allows a user to manage pods, services, configmaps, secrets, and deployments, but nothing else.

Apply it:

kubectl apply -f backend-role.yaml

Bind the role to a specific user or group

apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: deployer-binding
  namespace: production
subjects:
- kind: User
  name: [email protected]
  apiGroup: rbac.authorization.k8s.io
roleRef:
  kind: Role
  name: backend-deployer
  apiGroup: rbac.authorization.k8s.io

Apply and verify:

kubectl apply -f rolebinding.yaml
kubectl auth can-i create deployments --as [email protected] -n production

Expected output if the binding is correct:

yes

Test a permission that should be denied:

kubectl auth can-i delete namespaces --as [email protected]

Expected output:

no

Double-check with kubectl describe

kubectl describe rolebinding deployer-binding -n production

This shows the role reference and subjects. Verify there are no unexpected bindings.

3. Set Resource Quotas

Resource quotas prevent a single team or application from consuming all cluster resources. They enforce fairness and protect cluster stability.

Create a quota for the production namespace:

apiVersion: v1
kind: ResourceQuota
metadata:
  name: prod-quota
  namespace: production
spec:
  hard:
    requests.cpu: "10"
    requests.memory: 20Gi
    limits.cpu: "20"
    limits.memory: 40Gi
    persistentvolumeclaims: "5"
    pods: "20"
    services: "10"

Apply:

kubectl apply -f resourcequota.yaml

Verify:

kubectl describe resourcequota prod-quota -n production

You will see used vs hard limits. This helps you forecast capacity.

4. Set Limit Ranges

Limit ranges enforce default resource requests and limits on pods and containers that do not specify them. This prevents a pod from being created with no limits and unbounded memory.

apiVersion: v1
kind: LimitRange
metadata:
  name: prod-limits
  namespace: production
spec:
  limits:
  - default:
      cpu: "500m"
      memory: "512Mi"
    defaultRequest:
      cpu: "250m"
      memory: "256Mi"
    max:
      cpu: "2"
      memory: "2Gi"
    min:
      cpu: "100m"
      memory: "64Mi"
    type: Container

Apply and verify:

kubectl apply -f limitrange.yaml
kubectl describe limitrange prod-limits -n production

5. Enforce Pod Security Standards

Kubernetes provides built-in Pod Security Admission (PSA) that can enforce baseline or restricted profiles at the namespace level. The restricted profile is ideal for hardening but may break workloads that need elevated privileges.

Start with the baseline profile and then tighten gradually.

Label the namespace to enforce baseline:

kubectl label namespace production pod-security.kubernetes.io/enforce=baseline pod-security.kubernetes.io/audit=restricted pod-security.kubernetes.io/warn=restricted

This enforces baseline, but only warns and audits for restricted. After you fix workloads, you can switch enforce to restricted:

kubectl label --overwrite namespace production pod-security.kubernetes.io/enforce=restricted

Test by trying to create a privileged pod:

apiVersion: v1
kind: Pod
metadata:
  name: test-priv
  namespace: production
spec:
  containers:
  - name: busybox
    image: busybox
    command: ["sleep", "3600"]
    securityContext:
      privileged: true

Attempt to apply:

kubectl apply -f privileged-pod.yaml

You should see an error like:

Error from server (Forbidden): error when creating "privileged-pod.yaml": pods "test-priv" is forbidden: violates PodSecurity "restricted:latest": privileged (container "busybox" must not set securityContext.privileged=true)

That confirms the policy is active.

Verification and Diagnostics

Verification is not a one-time step. After each change, confirm the intended effect and watch for unintended consequences.

Verify Namespace Labels and Annotations

kubectl get namespace production -o yaml | grep -A5 "labels:"

Check that your security-related labels are present.

Verify RBAC Permissions

Use kubectl auth can-i extensively. Test with different users and service accounts. For service accounts:

kubectl auth can-i get pods --as=system:serviceaccount:production:default -n production

If you want to verify a service account's permissions before creating it, use a dry-run:

kubectl auth can-i create deployments --as=system:serviceaccount:production:ci-bot -n production

Verify Resource Quota Enforcement

Try to create a pod that exceeds the quota. For example, request 100 CPUs:

apiVersion: v1
kind: Pod
metadata:
  name: greedy-pod
  namespace: production
spec:
  containers:
  - name: busybox
    image: busybox
    resources:
      requests:
        cpu: "100"
        memory: "1Gi"

Apply and expect an error:

kubectl apply -f greedy-pod.yaml

Output should include something like:

Error from server (Forbidden): error when creating "greedy-pod.yaml": pods "greedy-pod" is forbidden: exceeded quota: prod-quota, requested: requests.cpu=100, used: requests.cpu=0, limited: requests.cpu=10

Verify Network Policy Enforcement (if applicable)

Network policies are a key namespace hardening tool. They restrict pod-to-pod communication. Without them, all pods can talk to each other across namespaces.

Create a default-deny policy for the namespace:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny
  namespace: production
spec:
  podSelector: {}
  policyTypes:
  - Ingress
  - Egress

Apply and then test connectivity from a pod in a different namespace:

# Run a test pod in default namespace
kubectl run test-pod --image=alpine --rm -it --restart=Never -- sh
# Inside the pod, try to curl a service in production namespace
wget -qO- http://backend-service.production.svc.cluster.local

If the network policy is enforced, the connection should hang or be refused. You can also use kubectl exec into an existing pod in production to test outbound access.

Verify Pod Security Admission

Check namespace labels:

kubectl get namespace production --show-labels

Look for pod-security.kubernetes.io/enforce=restricted. Then attempt to create a non-compliant pod as shown earlier.

Continuous Diagnostics

Set up periodic checks with a simple script or integrate into your CI/CD pipeline. For example, a script that runs kubectl auth can-i --list for all users in the namespace and diffs against expected permissions.

Failure Modes and Recovery

Even careful changes can break applications. This section describes common failures and how to recover.

Accidental Lockout from RBAC

Failure: You apply a RoleBinding that removes necessary permissions, and users can no longer deploy or even view pods.

Recovery: If you have cluster-admin access, fix the binding. If not, you need an emergency break-glass account. Best practice: maintain a separate cluster-admin kubeconfig stored securely for emergencies. Before making RBAC changes, always note the previous state with kubectl get rolebinding <name> -o yaml > backup.yaml. To restore, apply the backup:

kubectl apply -f backup.yaml

PodSecurity Policy Blocks Legitimate Workloads

Failure: After switching to restricted profile, pods fail to start because they require certain capabilities or hostPath volumes.

Recovery: Temporarily relax to baseline while you fix the workload:

kubectl label --overwrite namespace production pod-security.kubernetes.io/enforce=baseline

Then modify the pod spec to comply with restricted (remove privileged, add seccompProfile, etc.) and re-enforce.

Resource Quota Exceeded

Failure: Deployments fail because the namespace quota is exhausted. Users see errors like "exceeded quota".

Recovery: Check current usage:

kubectl describe resourcequota prod-quota -n production

Identify which resource is over limit. Then either scale down existing workloads, delete unused resources, or request a quota increase after capacity review. To temporarily allow deployments, you can increase the quota (but that may affect other teams).

Network Policy Cuts Off Legitimate Traffic

Failure: After applying a default-deny policy, services can no longer communicate, and health checks fail.

Recovery: Quickly delete the network policy:

kubectl delete networkpolicy default-deny -n production

Then add specific allow rules for required traffic. Start with a policy that allows ingress from the monitoring namespace and egress to DNS and external services.

Secrets Management Pitfalls

Failure: You store secrets as plain text in ConfigMaps or environment variables, and they leak via logs or version control.

Recovery: Move secrets to Kubernetes Secrets and use external secret management (e.g., HashiCorp Vault, AWS Secrets Manager, or Sealed Secrets). Ensure pods access secrets via volume mounts or projected volumes, not env vars. Rotate leaked secrets immediately.

Example of a secure secret:

apiVersion: v1
kind: Secret
metadata:
  name: db-credentials
  namespace: production
type: Opaque
stringData:
  username: app-user
  password: ${PLACEHOLDER_FROM_VAULT}

Use a placeholder here and inject the real value via a controller or external secrets operator.

Quick check 2 of 2

Which field is deprecated and read-only, representing a legacy reference to the object itself?

The passage explicitly states that selfLink is deprecated and is a legacy read-only field.

Operations Checklist

Use this checklist before and after namespace hardening to ensure consistency and safety.

Pre-change Checklist

  • [ ] Verify cluster and client versions match within supported skew.
  • [ ] Capture baseline of namespace resources, RBAC, quotas, and labels.
  • [ ] Identify who will be affected by the change (users, service accounts, applications).
  • [ ] Review the change in a non-production namespace first.
  • [ ] Prepare rollback plan: save current YAML for any object you will modify.

Implementation Steps (one at a time, verify after each)

  • [ ] Apply namespace labels for organizational clarity.
  • [ ] Apply RBAC role and bindings; test with kubectl auth can-i.
  • [ ] Apply resource quota and limit range; verify with kubectl describe.
  • [ ] Label namespace for Pod Security Admission; start with audit and warn, then enforce.
  • [ ] Apply network policies; test connectivity.
  • [ ] Review secrets handling; ensure no plain text secrets in configs.

Post-change Verification

  • [ ] Run kubectl get all -n production to confirm all workloads are Running.
  • [ ] Check events: kubectl get events -n production --sort-by=.lastTimestamp.
  • [ ] Review logs for new errors: kubectl logs -l app=your-app -n production --tail=50.
  • [ ] Confirm RBAC works for all expected users and service accounts.
  • [ ] Confirm quota and limit ranges are enforced (try exceeding them intentionally in a test).

Ownership and Review Cadence

  • Namespace owner: Assign a single person responsible for the namespace security posture. In a startup, this might be the backend lead or platform engineer.
  • Review frequency: Revisit security settings monthly and after any major release or incident. Keep a log of changes with timestamps and approvals.

Common Pitfalls and How to Avoid Them

Using ClusterRoleBinding Instead of RoleBinding

ClusterRoleBinding grants permissions across all namespaces. Often, developers use it out of convenience, but it violates least privilege. Avoid: Use RoleBinding within the namespace unless the role truly needs cluster-wide scope. If you must use ClusterRole, bind it to a specific namespace using RoleBinding referencing a ClusterRole.

Not Setting Default Deny Network Policies

Many teams rely on namespace isolation, but by default all pods can communicate across namespaces. Avoid: Apply a default-deny policy in every namespace, then add explicit allow rules for required traffic.

Ignoring Pod Security Standards

Running privileged containers is common in development but dangerous in production. Avoid: Enforce at least baseline, and strive for restricted. Use audit mode to discover non-compliant workloads before enforcement.

Overly Permissive Service Account Tokens

By default, every pod has a service account token mounted. If the pod is compromised, the attacker can use that token to access the API. Avoid: Disable auto-mounting of service account tokens unless necessary (automountServiceAccountToken: false in pod spec) and assign minimal RBAC to service accounts.

Secrets in Environment Variables

Environment variables are visible in process listings and can leak through crash dumps or logging. Avoid: Mount secrets as files, and use a secrets management solution.

Conclusion

Hardening Kubernetes namespaces requires a systematic approach: know your environment, apply least privilege access control, limit resource consumption, enforce pod security standards, restrict network traffic, and manage secrets carefully. Each change should be observable, verifiable, and reversible when possible.

Start with one low-risk improvement: for example, label your namespace and apply a ResourceQuota. Record the current state, run the documented commands, and compare the results with expected output. Then move on to RBAC and Pod Security Admission.

A reliable workflow makes failure visible, protects sensitive values, limits changes to the intended resource, and defines recovery verification before an incident forces the decision. With the practical examples in this article, you can begin hardening your namespaces today and build a more secure Kubernetes cluster.

Related Research

Article Quality Score

Reader usefulness 100%
  • check_circle Reader-ready guide
  • check_circle Practical examples included
  • check_circle Clean SEO article URL