How to add user to docker group

How to add user to docker group

Post-installation steps for Linux

Estimated reading time: 16 minutes

This section contains optional procedures for configuring Linux hosts to work better with Docker.

Manage Docker as a non-root user

The docker group grants privileges equivalent to the root user. For details on how this impacts security in your system, see Docker Daemon Attack Surface.

To create the docker group and add your user:

Create the docker group.

Add your user to the docker group.

Log out and log back in so that your group membership is re-evaluated.

If testing on a virtual machine, it may be necessary to restart the virtual machine for changes to take effect.

On a desktop Linux environment such as X Windows, log out of your session completely and then log back in.

On Linux, you can also run the following command to activate the changes to groups:

This command downloads a test image and runs it in a container. When the container runs, it prints a message and exits.

If you initially ran Docker CLI commands using sudo before adding your user to the docker group, you may see the following error, which indicates that your

/.docker/ directory was created with incorrect permissions due to the sudo commands.

To fix this problem, either remove the

/.docker/ directory (it is recreated automatically, but any custom settings are lost), or change its ownership and permissions using the following commands:

Configure Docker to start on boot

Most current Linux distributions (RHEL, CentOS, Fedora, Debian, Ubuntu 16.04 and higher) use systemd to manage which services start when the system boots. On Debian and Ubuntu, the Docker service is configured to start on boot by default. To automatically start Docker and Containerd on boot for other distros, use the commands below:

To disable this behavior, use disable instead.

If you need to add an HTTP Proxy, set a different directory or partition for the Docker runtime files, or make other customizations, see customize your systemd Docker daemon options.

Use a different storage engine

For information about the different storage engines, see Storage drivers. The default storage engine and the list of supported storage engines depend on your host’s Linux distribution and available kernel drivers.

Configure default logging driver

To alleviate such issues, either configure the json-file logging driver to enable log rotation, use an alternative logging driver such as the “local” logging driver that performs log rotation by default, or use a logging driver that sends logs to a remote logging aggregator.

Configure where the Docker daemon listens for connections

By default, the Docker daemon listens for connections on a UNIX socket to accept requests from local clients. It is possible to allow Docker to accept requests from remote hosts by configuring it to listen on an IP address and port as well as the UNIX socket. For more detailed information on this configuration option take a look at “Bind Docker to another host/port or a unix socket” section of the Docker CLI Reference article.

Before configuring Docker to accept connections from remote hosts it is critically important that you understand the security implications of opening docker to the network. If steps are not taken to secure the connection, it is possible for remote non-root users to gain root access on the host. For more information on how to use TLS certificates to secure this connection, check this article on how to protect the Docker daemon socket.

Configuring Docker to accept remote connections can be done with the docker.service systemd unit file for Linux distributions using systemd, such as recent versions of RedHat, CentOS, Ubuntu and SLES, or with the daemon.json file which is recommended for Linux distributions that do not use systemd.

Configuring Docker to listen for connections using both the systemd unit file and the daemon.json file causes a conflict that prevents Docker from starting.

Configuring remote access with systemd unit file

Use the command sudo systemctl edit docker.service to open an override file for docker.service in a text editor.

Add or modify the following lines, substituting your own values.

How can I use docker without sudo?

How can I configure Docker so that I don’t need to prefix every Docker command with sudo?

5 Answers 5

Good news: the new docker (version 19.03 (currently experimental)) will be able to run rootless negating the problems that can occur using a root user. No more messing with elevated permissions, root and anything that might open up your machine when you did not want to.

A few Caveats to the rootless Docker mode

Docker engineers say the rootless mode cannot be considered a replacement for the complete suite of Docker engine features. Some limitation to the rootless mode include:

As of docker 19.3 this is obsolete (and more dangerous than need be):

The docker manual has this to say about it:

Giving non-root access

The docker daemon always runs as the root user, and since Docker version 0.5.2, the docker daemon binds to a Unix socket instead of a TCP port. By default that Unix socket is owned by the user root, and so, by default, you can access it with sudo.

In the recent release of the experimental rootless mode on GitHub, engineers mention rootless mode allows running dockerd as an unprivileged user, using user_namespaces(7), mount_namespaces(7), network_namespaces(7).

Users need to run dockerd-rootless.sh instead of dockerd.

As Rootless mode is experimental, users need to always run dockerd-rootless.sh with –experimental.

Manage Docker as a non-root user

The docker daemon binds to a Unix socket instead of a TCP port. By default that Unix socket is owned by the user root and other users can only access it using sudo. The docker daemon always runs as the root user.

If you don’t want to use sudo when you use the docker command, create a Unix group called docker and add users to it. When the docker daemon starts, it makes the ownership of the Unix socket read/writable by the docker group.

Add the docker group if it doesn’t already exist:

Add the connected user «$USER» to the docker group. Change the user name to match your preferred user if you do not want to use your current user:

Either do a newgrp docker or log out/in to activate the changes to groups.

to check if you can run docker without sudo.

Пользователь в Docker

Андрей Копылов, наш технический директор, любит, активно использует и пропагандирует Docker. В новой статье он рассказывает, как создать пользователей в Docker. Правильная работа с ними, почему пользователей нельзя оставлять с root правами и, как решить задачу несовпадения идентификаторов в Dockerfile.

Все процессы в контейнере будут работать из-под пользователя root, если специальным образом его не указать. Это кажется очень удобно, ведь у этого пользователя нет никаких ограничений. Именно поэтому работать под рутом неправильно с точки зрения безопасности. Если на локальном компьютере никто в здравом уме не работает с рутовыми правами, то многие запускают процессы под рутом в контейнерах.

Всегда есть баги, которые позволят зловреду выбраться из контейнера и попасть на хостовый компьютер. Предполагая худшее, мы должны обеспечить запуск процессов внутри контейнера от пользователя, который не имеет никаких прав на хостовой машине.

Создание пользователя

Создание пользователя в контейнере не отличается от его создания в линуксовых дистрибутивах. Однако для разных базовых образов команды могут различаться.

Для дистрибутивов основанных на debian в Dockerfile необходимо добавить:

Запуск процессов от пользователя

Для запуска всех последующих процессов от пользователя с UID 2000 выполните:

Для запуска всех последующих процессов от пользователя node выполните:

Монтирование томов

При монтировании томов внутрь контейнера обеспечьте пользователю возможность читать и (или) писать файлы. Для этого UID (GID) пользователя в контейнере и пользователя за пределами контейнера, у которого есть соответствующие права на доступ к файлу, должны соответствовать. При этом имена пользователей значения не имеют.

Часто на линуксовом компьютере у пользователя UID и GID равны 1000. Эти идентификаторы присваиваются первому пользователю компьютера.

Узнать свои идентификаторы просто:

Вы получите исчерпывающую информацию о своем пользователе.
Замените 2000 из примеров на свой идентификатор и все будет в порядке.

Присвоение пользователю UID и GID

Если пользователь создан ранее, но необходимо изменить идентификаторы, то можно сделать это так:

Если вы используете базовый образ alpine, то нужно установить пакет shadow:

Передача идентификатора пользователя внутрь контейнера при построении образа

Если ваш идентификатор и идентификаторы всех людей, которые работают над проектом, совпадают, то достаточно указать этот идентификатор в Dockerfile. Однако часто идентификаторы пользователей не совпадают.

Как осуществить желаемое не сразу понятно. Для меня это было самым сложным в процессе освоения docker. Многие пользователи docker не задумываются о том, что есть разные этапы жизни образа. Сначала образ собирается для этого используют Dockerfile. При запуске контейнера из образа Dockerfile уже не используется.

Создание пользователей должно происходить при построении образа. Это же касается и определения пользователя, из-под которого запускаются процессы. Значит, что мы каким-то образом должны передать внутрь контейнера UID (GID).

Для использования внешних переменных в Dockerfile служат директивы ENV и ARG. Подробное сравнение директив тут.

Передать аргументы через docker-compose можно так:

Run Docker as a non-root user

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:

3. Add your user to the docker group:

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:

2. Proceed to build the Docker image using the “docker build” subcommand, as depicted here:

3. Finally, let’s verify the current user of our container using the id command in a docker run subcommand:

Evidently, the container’s user, group, and the groups are now changed to a non-root user.

How to set user and group in Docker Compose

How to add user to docker group. Смотреть фото How to add user to docker group. Смотреть картинку How to add user to docker group. Картинка про How to add user to docker group. Фото How to add user to docker group

I have this problem: a client’s DevOps is a Mac user, meaning that their Docker works differently on my Linux machine¹. In this case we talk about user and group.

When I create a file using Docker (or, in my case, Docker Compose, the logic is the same in general), the file is created with root privileges, so I cannot directly edit them unless I chown them.

To avoid this we have to set user and group IDs somewhere. There are multiple solutions to this problem: I’ll name a few.

This is our initial docker-compose.yml:

I’m told this works out of the box on Mac (I haven’t personally checked), while on Linux, if I run a command, I get a couple of interesting warnings, meaning that the command will be run as root.

How can we avoid those warning, and actually set the ownership to my user (which is 1001:1001 on my current machine) while using Docker?

Here are six ways to do it (remember to open a new terminal after each one).

Solution 1: Add variables to the command

This is quick but not ideal:

Solution 2: Variable export

This will work as long as we stay in the current shell. There is margin for some kind of improvement…

Solution 3: Store the variables in the config

/.bashrc file (works in other shells, of course) append these two lines:

Then refresh the file (or open a new terminal):

and run the usual command:

Solution 4: put the user IDs in the command itself

This is the most straightforward, I guess…

The problem is that less Docker-savvy coworkers will need to remember to do this. All. The. Time.

Solution 6: use an override

(Of course this is the solution the DevOps actually implemented after noticing Linux developers screaming all over the (virtual) office).

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *