Penguin-KarChunTKarChunT

Security Context

Understand how to use security context in Kubernetes.

Concept and Usage of Security Context

Security context defines privilege and access control settings for a Pod or Container. So, we can choose to configure the security context at the Pod level or at the Container level.

security-context.yaml
apiVersion: v1
kind: Pod
metadata:
  name: sample-pod
spec:
  securityContext:
    runAsUser: 1000 # Run as user with UID 1000
  containers:
    - name: ubuntu
      image: ubuntu
      command: ["sleep", "3600"]
      securityContext:
        runAsUser: 2000 # This will override the Pod level security context
        capabilities:
          add: ["NET_ADMIN", "SYS_TIME", "MAC_ADMIN"]
  • Remember, the security context defined at the Container level will override the Pod level security context.

  • capabilities field is used to add or drop capabilities for a container, it is only supported at the container level, not at the pod level.

    • capabilities are a fine-grained way to control the privileges of processes. By adding specific capabilities, you can grant a container additional privileges without giving it full root access.
  • For runAsUser, you need to tied it with the user in the Dockerfile when you create a username with uid in the Dockerfile. For example, you have a Dockerfile like this, then in the security context you can use runAsUser: 1000 to run the container with the user myuser with, so the container will refer to the user myuser with uid 1000 in the Dockerfile.

    Dockerfile
    FROM ubuntu:latest
    RUN useradd -u 1000 -m myuser
    USER myuser
    CMD ["bash"]

On this page