Home > Operation and Maintenance > Docker > How to switch to normal user in docker

How to switch to normal user in docker

PHPz
Release: 2023-04-10 09:06:04
Original
4045 people have browsed it

In Docker, in order to achieve more secure operations, non-root users are usually used to run containers, because the root user has full permissions to perform any operations inside the container. In this article, we will explain how to switch to a non-root user.

1. Create a non-root user

Before using Docker, we need to create a non-root user. To do this, we can create it in the following way:

  1. Execute the following command to create a user named "dockeruser":
sudo useradd -ms /bin/bash dockeruser
Copy after login
  1. This is the user Set password:
sudo passwd dockeruser
Copy after login
  1. Add this user to the docker user group:
sudo usermod -aG docker dockeruser
Copy after login

2. Switch to a normal user in the container

  1. Use the following command to start the container:
docker run -it --name mycontainer ubuntu:latest /bin/bash
Copy after login
  1. Inside the container, switch to an ordinary user:
su dockeruser
Copy after login

3. Use Dockerfile to switch to an ordinary user

Using Dockerfile can more easily automate the container building process. The following is an example of using a Dockerfile to implement non-root user switching:

  1. Create a file named "Dockerfile" and add the following content:
FROM ubuntu:latest

RUN groupadd -g 1000 dockeruser && \
    useradd -r -u 1000 -g dockeruser dockeruser

USER dockeruser
Copy after login
  1. Build the image and start the container:
docker build -t myimage .
docker run -it --name mycontainer myimage /bin/bash
Copy after login

Here we create a user named "dockeruser" through the Dockerfile and set it as the default user when the container starts.

Summary

Using non-root users to run containers in Docker can improve security and protect the host system and sensitive data. In this article, we covered two methods of switching to a non-root user: manually switching in the container and automatically using a Dockerfile.

With the development of container technology, we believe that more security and convenience features will be introduced into Docker. If you also want to learn more about Docker containers, please follow our blog.

The above is the detailed content of How to switch to normal user in docker. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template