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.
id
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.
FROM base_image
# Create a non-root user
RUN useradd -ms /bin/bash newuser
# Set the new user as the default user
USER newuser
Set Home Directory:
Ensure that the home directory for the new user is properly set.
ENV HOME /home/newuser
WORKDIR $HOME
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.
USER newuser
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
Test Permissions:
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.
whoami
Verify Home Directory:
Confirm that the home directory for the new user is correctly set.
echo $HOME
Cleanup:
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.
Top comments (0)