In this lesson, we will explore the basics of securing your Kubernetes cluster and applications. Security is a critical aspect of any deployment, and Kubernetes provides various mechanisms to help you secure your applications and the cluster itself.
RBAC is a method for regulating access to resources based on the roles of individual users within your organization. In Kubernetes, you can define roles and role bindings to control who can perform actions on what resources.
Here's an example of how to create a role and a role binding:
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
namespace: default
name: pod-reader
rules:
- apiGroups: [""] # core API group
resources: ["pods"]
verbs: ["get", "list", "watch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: read-pods-binding
namespace: default
subjects:
- kind: User
name: jane
apiGroup: rbac.authorization.k8s.io
roleRef:
kind: Role
name: pod-reader
apiGroup: rbac.authorization.k8s.io
Network Policies are used to control the traffic flow between pods. They define rules about which pods can communicate with each other.
This example restricts access to a pod so that only pods with the label role: frontend can communicate with it:
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-frontend
namespace: default
spec:
podSelector:
matchLabels:
role: backend
policyTypes:
- Ingress
ingress:
- from:
- podSelector:
matchLabels:
role: frontend
Pod Security Policies are cluster-level resources that control security-sensitive aspects of the pod specification. Note that PSP is deprecated in newer Kubernetes versions; consider using alternatives like OPA/Gatekeeper.
Ensure that you use trusted images and scan them for vulnerabilities. You can use tools like Trivy to scan your container images.
To scan an image named myapp:latest, you can run:
trivy image myapp:latest
Avoid hardcoding sensitive information in your deployments. Use Kubernetes Secrets instead. Do not expose unnecessary services to the internet. Use Ingress resources and Network Policies to control access.
| Security Mechanism | Description |
|---|---|
| Role-Based Access Control (RBAC) | Controls access to resources based on user roles. |
| Network Policies | Controls traffic flow between pods. |
| Pod Security Policies | Enforces security standards on pod specifications. |
| Image Security | Ensures container images are trusted and vulnerability-free. |
Create an RBAC Role and RoleBinding
- Create a Role that allows a user to list and get pods in the default namespace.
- Bind this role to a user named alice.
Implement a Network Policy
- Create a Network Policy that allows traffic to a backend pod only from frontend pods.
- Test the policy by trying to access the backend pod from another pod.
Scan a Docker Image
- Pull a public Docker image (e.g., nginx:latest) and scan it using Trivy.
- Review the results and identify any vulnerabilities.