By default, a Docker Container runs as a Root user. This poses a great security threat if you deploy your applications on a large scale inside Docker Containers. You can change or switch to a different user inside a Docker Container using the USER Instruction. For this, you first need to create a user and a group inside the Container.
In this article, we are going to use the USER instruction to switch the user inside the Container from Root to the one which we will create. To do so follow the below steps:
Step 1: Create the Dockerfile
You can specify the instructions to create a new user and group and to switch the user both in the Dockerfile. For this example, we will simply create an Ubuntu Image and use the bash with a different user other than the Root user.
FROM ubuntu:latest RUN apt-get -y update RUN groupadd -r user && useradd -r -g user user USER user
In the above dockerfile, we have pulled the base Image Ubuntu and updated it. We have created a new group called user and a new user inside the group with the same name. Using the USER option, we have then switched the user.
Step 2: Build the Docker Image
After creating the Dockerfile, we can now create the Docker Image using the Build command.
sudo docker build -t user-demo .
Step 3: Run the Docker Container
Use the Docker Run command to run the Container.
sudo docker run -it user-demo bash
Step 4: Verify the output
You can now check that the default user and the group have now changed to the one we created in the Dockerfile using the id command.
To conclude, in this article we discussed how to use the USER instruction inside the Dockerfile to switch the Docker Container’s default user from Root to another user that we can create using the useradd and grouadd commands.