Root User and Password in a Container

This article is translated from “Root User and Password Inside a Docker Container”

We often open Docker containers with root privileges, which obviously has certain security issues. This article will discuss how to create Docker images using non-root users to ensure the security of some resources.

1
2
3
4
5
FROM ubuntu:16.04
RUN apt-get update
RUN useradd -m john
USER john
CMD /bin/bash
DOCKER

The above example creates an image of a non-root user. After a normal startup, when entering the container, you will log in as the user john. At this time, if you use the package manager to install software packages, you will report an insufficient permission error and need to switch to the root user. When you are bothered by the prompt to enter the password of the root account when switching, there is a simple way to log in directly as the root user, which is to use the following command.

1
docker exec -it -u 0 container_name bash
SHELL

Of course, you can also use the following command

1
docker exec -it -u root container_name bash
SHELL

If you must specify special privileges for non-root users in the container, you can also install the sudo command. The following example creates a non-root user john and grants him sudo privileges

1
2
3
4
5
FROM ubuntu:16.04
RUN apt-get update && apt-get -y install sudo
RUN useradd -m john && echo "john:john" | chpasswd && adduser john sudo
USER john
CMD /bin/bash
DOCKER

User Mapping Issues

Usually, after creating a container using the docker run -itd --user `id -u`:`id -g` xxxx command and entering the system, an error that the user cannot be found will be reported. At this time, you can first check the uid and gid outside. Then enter the root mode of the container and modify the uid and gid of the user in the container to the correct mapping.

1
2
usermod -u 1000 ubuntu
groupmod -g 100 ubuntu
SHELL
Licensed under CC BY-NC-SA 4.0

请在评论前阅读我们的评论政策


内容是由智能博客生成器生产 powered by ChatGGPTT
Built with Hugo
Theme Stacked designed by Jimmy, modified by Jacob