securityContext. That can result in containers running with broader kernel capabilities or as the root user. If a container does not require elevated privileges or root access, it’s safer to explicitly restrict those capabilities.
A recommended hardening step is to set container-level securityContext fields and make the container root filesystem read-only. A readOnlyRootFilesystem: true reduces the blast radius of a compromise because an attacker cannot persist files to the root filesystem. When enabling read-only root filesystem, you must also mount any directories your application needs to write to (for example /tmp) as writable volumes.
Below is a consolidated Deployment manifest that includes node selection, environment variables, resource requests, a memory-backed emptyDir for /tmp, and explicit container security settings (non-privileged, read-only root filesystem, no privilege escalation).
deployment.yaml) and apply it to your OpenShift cluster:
Best practice: When enabling
readOnlyRootFilesystem: true, explicitly mount any directories the application needs to write to (for example /tmp) as writable volumes. Otherwise the container may fail at runtime due to write failures.Be aware of two common pitfalls with these settings:
-
runAsNonRoot: truewill cause the pod to fail to start if the container image expects to run as root. If the image runs as root by default, either remove this flag or set an explicit non-root UID withrunAsUser(and ensure the image supports that UID). -
readOnlyRootFilesystemplus only an ephemeral memory-backedemptyDirat/tmpis not sufficient for stateful services like MongoDB. The MongoDB image typically requires a writable data directory (for example/var/lib/mongodbor the image-specific data path) which should be backed by aPersistentVolumeClaimfor durability. Also note thatemptyDirwithmedium: Memoryis ephemeral (tmpfs) and will be lost when the pod restarts.
Further reading and references
- Kubernetes Pods and Containers
- Kubernetes Pod SecurityContext
- OpenShift Web Console docs
- Best practices for running containers securely