Dockerfile User and Kubernetes Security Context

Security, Security, Security!

As containerisation is becoming more and more popular in the form of migrating apps to Docker containers and running them on Kubernetes hosts, it is important to not forget about security best practices for Docker and Kubernetes during migration or when creating them from scratch, as putting this off or forgetting about them can have a huge impact.

If your containers or Kubernetes pods are not secured properly it could allow bad actors to compromise your app and gain root permissions to the container and even the host, causing major disruption or even extract private data.

Two security features I suggest every developer use, unless there is specific need to run the apps as root, are Dockerfile User setting and Kubernetes Security Context.

Dockerfile User setting:

Dockerfiles allow you to specify how a container should be built and the settings it should contain ranging from base image (unix, ubuntu, redhat), working directory to volumes that should be attached to it. One of the most important things to remember when creating your container is if you do not specify a User setting for the container to run, it will run as ROOT (which is very insecure and could allow the issues mentioned above). A TIP to remember when building your container is to make sure you give it a User context and ideally a unique UID and GUID to run as.

https://docs.docker.com/develop/develop-images/dockerfile_best-practices/

https://medium.com/digio-australia/securing-your-container-workloads-in-kubernetes-369d18c2a006

Kubernetes Security Context:

K8 security context is a security feature that can be applied at the pod or container level, its purpose is to secure the pod or container it is deployed on to prevent bad actors from elevating their permissions or trying to access the host the pod is running on for example. The good thing is that Dockerfile User setting and Kubernetes security context go hand in hand as when you are creating your deployment file for the pod or container you are able to reference the User given in the Dockerfile so the pod knows what user the container should run as and what the user is allowed to do.

Adding the above in to your deployment or cron job yaml will secure your pod or container and is the best practice advised by Kubernetes. If you would like to know what each of these settings means please see the Kubernetes site below for more details.

https://kubernetes.io/docs/tasks/configure-pod-container/security-context/

Hope this has helped and if you have any questions or anything to add please comment below 🙂