By default, Docker Containers run as Root Users. Now, if you are running applications inside Docker Containers, you have access to all the root privileges. This poses a great security threat when you deploy applications on large scale inside Docker Containers. Because if somehow your application gets hacked by external users, other applications running inside the Containers would also be a huge risk. Moreover, if your Docker Container is part of a network, then the whole network has the risk of getting hacked. To avoid this, you need to make sure that you run the Docker Containers as non-root users.
In this article, we will discuss two different ways using which you can create and add non-root users inside Docker Containers.
Method 1: Specify in Dockerfile
You can add users using the -u option along with useradd. You can then use the USER instruction to switch the user. Consider the Dockerfile below.
FROM ubuntu RUN useradd -u 1234 my-user USER my-user
The above Dockerfile pulls the Ubuntu base image and creates a user with ID 1234 and name my-user. It then switches to the new user using the USER instruction.
Now, to build the Image, use the Docker Build command.
sudo docker build -t nonroot-demo .
Use the Docker Run command to run the container.
sudo docker run -it nonroot-demo bash
You can see that the user has been changed to the non-root user that we created in the Dockerfile.
Method 2: By adding a user to the Docker group
To create a Docker group, you can use the following command.
sudo groupadd docker
If there is already a docker group, you will get the following output –
Now, to create a non-root user and add it to the docker group, you can use the following command.
sudo useradd -G docker <user-name>
After that, you can assign a password to the user using the following command.
sudo passwd user
To change a user’s primary group, use this command.
sudo usermod -aG docker <non-root user>
Restart the Docker service.
Attention reader! Don’t stop learning now. Get hold of all the important CS Theory concepts for SDE interviews with the CS Theory Course at a student-friendly price and become industry ready.