The Docker containers by default run with the root privilege and so does the application that runs inside the container. This is another major concern from the security perspective because hackers can gain root access to the Docker host by hacking the application running inside the container.
Method 1 – Add user to Docker group
1. To run Docker as a non-root user, you have to add your user to the docker group.
2. Create a docker group if there isn’t one:
$ sudo groupadd docker
3. Add your user to the docker group:
$ sudo usermod -aG docker [non-root user]
4. Log out and log back in so that your group membership is re-evaluated.
Method 2 – Using Dockerfile (USER instruction)
Docker provides a simple yet powerful solution to change the container’s privilege to a non-root user and thus thwart malicious root access to the Docker host. This change to the non-root user can be accomplished using the -u or –user option of the docker run subcommand or the USER instruction in the Dockerfile.
1. Edit the Dockerfile that creates a non-root privilege user and modify the default root user to the newly-created non-root privilege user, as shown here:
########################################## # Dockerfile to change from root to # non-root privilege ########################################### # Base image is CentOS 7 FROM Centos:7 # Add a new user "john" with user id 8877 RUN useradd -u 8877 john # Change to non-root privilege USER john
2. Proceed to build the Docker image using the “docker build” subcommand, as depicted here:
$ sudo docker build -t nonrootimage .
3. Finally, let’s verify the current user of our container using the id command in a docker run subcommand:
$ sudo docker run --rm nonrootimage id uid=8877(john) gid=8877(john) groups=8877(john)
Evidently, the container’s user, group, and the groups are now changed to a non-root user.