Run nginx as unprivileged user in Docker container on Kubernetes

Run nginx as unprivileged user in Docker container on Kubernetes

While on production, it is important to run your containers as non root users to avoid any security vulnerabilities.

The rationale

From security perspective, running a process on container as root user is as bad as running a process as root on host machine itself. If a user manages to break out of an application running as root in a container, he may be able to gain access to the host with the same root user. More information about this can be found at this interesting blog post.


We will be using helm for deploying our nginx application on kubernetes.

Create helm charts

The first thing we need to create is a deployment.yaml. The most basic deployment.yaml as given on official kubernetes docs looks like this. Here we have used the nginx unprivileged docker image instead of the nginx image. We can trust this image because it is also maintained and published by nginxinc.

If you’re not using custom config files for nginx, that should be all, in order to use this image. But, since in most cases, we need to use custom configs to be mounted on our pods, the deployment.yaml would look like this.

In this case, we need to make sure our configs are using the right defaults as mentioned in Readme of the unprivileged docker image we’re using. That basically means changing default values of some directives . Our basic configmap will look like below. The comments in example mentions the changed values.

Notice that we’re not using any user directive in our config.

Now we will create a service to direct traffic to our pods created from deployment.yaml. Create a basic service as mentioned in kubernetes documentation.

The service will now target port 8080 on the pods labelled nginx.

You can try and test out the deployment using

helm install nginx