Open In App
Related Articles

Running Docker Containers as Non-Root User

Improve Article
Save Article
Like Article

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 .

Specify in Dockerfile

Use the Docker Run command to run the container.

sudo docker run -it nonroot-demo bash

nonroot docker demo

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 – 

adding a user to the Docker group

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

assign a password

To change a user’s primary group, use this command.

sudo usermod -aG docker <non-root user>

Restart the Docker service.

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 05 Nov, 2020
Like Article
Save Article
Similar Reads