<!--
title: Harden container security
domain: ml-systems
topic: Security
language: Dockerfile
source: kubeflow/kubeflow
updated: 2024-06-30
url: https://awesomereviewers.com/reviewers/kubeflow-harden-container-security/
-->

When building container images, ensure they're compatible with restricted Kubernetes security contexts. Use numeric UIDs instead of symbolic usernames, and test compatibility with the following security constraints:

```yaml
securityContext:
  runAsNonRoot: true
  allowPrivilegeEscalation: false
  capabilities:
    drop:
      - ALL
```

This approach prevents privilege escalation attacks and follows the principle of least privilege. For example, in a Dockerfile, prefer `USER 1000` over `USER jovyan` to ensure compatibility with security contexts that enforce non-root execution. This practice enhances security in various Kubernetes environments, including those that don't automatically apply these restrictions.
