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.
RUN apt-get -y update
RUN groupadd -r user && useradd -r -g 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
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 groupadd commands.
Switching from the root user to another user inside a container is a good practice for security reasons. Here's a checklist for switching users inside a container, assuming you are working with a Docker image that doesn't have a specific user created:
Create a Non-Root User:
Create a new user within your Dockerfile using the USER and RUN commands.
# Create a non-root user
RUN useradd -ms /bin/bash newuser
# Set the new user as the default user
Set Home Directory:
Ensure that the home directory for the new user is properly set.
ENV HOME /home/newuser
Grant Necessary Permissions:
If your application requires specific permissions, grant them to the new user using chown or other commands.
RUN chown -R newuser:newuser /app
Switch to the New User:
Use the USER command in your Dockerfile to switch to the new user.
Specify User in Docker Run Command:
When running your container, you can override the default user using the --user option.
docker run --user newuser your_image
Ensure that the new user has the necessary permissions to execute the application.
docker exec -it your_container sh
Verify User Switch:
Inside the container, check the current user to ensure it has switched successfully.
Verify Home Directory:
Confirm that the home directory for the new user is correctly set.
Remove unnecessary files and packages used only for user creation in the Dockerfile to reduce the image size.
RUN apt-get purge -y --auto-remove $buildDeps
Ensure Security Best Practices:
Following the principle of least privilege, limit the permissions of the new user to the minimum required for the application to run.