Mastering Kubernetes from Scratch Part 15 - Understanding Security Context
Introduction to Security Context
What is a Security Context?
A Security Context in Kubernetes defines privileges and access controls for Pods and containers. It helps enforce security policies, limit permissions, and reduce risks.
Use-cases
Some of the common use-cases include:
Setting user and group IDs by using
runAsUser, runAsGroup,
andfsGroup.
Managing file system permissions. For instance, using
readOnlyRootFilesystem
to define the root filesystem as read-only.Restricting network access by setting NET_RAW to prevent the container from sending or receiving raw packets.
Enforcing privilege escalation policies.
Controlling Linux capabilities like
NET_ADMIN
orSYS_TIME
.
and many more.
Pod vs. Container Level Security Context
You can apply the security context on a Pod or Container level:
Pod Level: Applies to all containers within the Pod.
Container Level: Applies only to a specific container inside the Pod. The settings override Pod-level settings.
For example:
apiVersion: v1
kind: Pod
metadata:
name: secure-pod
spec:
securityContext: # Applies to all containers in the Pod
runAsUser: 1000 # The container runs as user ID 1000
runAsGroup: 3000 # The container's group ID is 3000
fsGroup: 2000 # Files created by the container belong to group 2000
containers:
- name: secure-container
image: busybox
command: [ "sh", "-c", "sleep 3600" ]
securityContext: # Overrides Pod-level settings for this container
allowPrivilegeEscalation: false # Prevents gaining more privileges
readOnlyRootFilesystem: true # Makes the root filesystem read-only
Best Practices: Strengthen Your Security Context
While security contexts offer many features, here are the ones you should implement right away:
Set
runAsNonRoot: true
to prevent containers from running as root.Enable
readOnlyRootFilesystem: true
to prevent writes to the container's root filesystem.Disable
allowPrivilegeEscalation
to prevent processes from gaining more privileges.Use RuntimeDefault seccomp profiles to filter system calls.
Document exceptions: Some legacy applications might require root access or specific capabilities. Document these exceptions and review them regularly.
Common Pitfalls to Avoid
Keep reading with a 7-day free trial
Subscribe to Curious Devs Corner to keep reading this post and get 7 days of free access to the full post archives.