Запуск демона Docker от имени пользователя, не являющихся пользователями root (режим rootless)
Режим Rootless позволяет запускать демон Docker и контейнеры от имени пользователя, не являющегося пользователем root, чтобы уменьшить потенциальные уязвимости в демоне и среде выполнения контейнеров.
Режим Rootless не требует привилегий root даже во время установки демона Docker, если соблюдены предварительные условия.
Режим Rootless был представлен в Docker Engine v19.03 в качестве экспериментальной функции. Режим Rootless стал экспериментальным в Docker Engine v20.10.
Как это работает.
Режим Rootless выполняет демон Docker и контейнеры внутри пространства имен пользователя. Это очень похоже на режим userns-remap, за исключением того, что в режиме userns-remap сам демон работает с правами root, тогда как в режиме rootless и демон, и контейнер работают без прав root.
Режим Rootless не использует двоичные файлы с битами SETUID или файловые возможности, за исключением newuidmap и newgidmap, которые необходимы для того, чтобы позволить использовать несколько UID/GID в пространстве имен пользователя.
Необходимые условия.
-
Необходимо установить
newuidmapиnewgidmapна хосте. Эти команды предоставляются пакетомuidmapв большинстве дистрибутивов. -
/etc/subuidи/etc/subgidдолжны содержать не менее 65 536 подчиненных UID/GIID для пользователя. В следующем примере пользователь -testuserимеет 65 536 подчиненных UIDs/GIDs (231072-296607).
$ id -u 1001 $ whoami testuser $ grep ^$(whoami): /etc/subuid testuser:231072:65536 $ grep ^$(whoami): /etc/subgid testuser:231072:65536
Подсказка для конкретного дистрибутива.
Примечание: Мы рекомендуем использовать ядро Ubuntu.
Ubuntu.
-
Установите пакет
dbus-user-session, если он не установлен. Выполнитеsudo apt-get install -y dbus-user-sessionи повторно войдите в систему. -
драйвер хранилища
overlay2включен по умолчанию(патч ядра, специфичный для Ubuntu). -
Известно, что работает на Ubuntu 18.04, 20.04 и 21.04.
Debian GNU/Linux.
-
Установите пакет
dbus-user-session, если он не установлен. Выполнитеsudo apt-get install -y dbus-user-sessionи повторно войдите в систему. -
Для Debian 10 добавьте
kernel.unprivileged_userns_clone=1в/etc/sysctl.conf(или/etc/sysctl.d) и запуститеsudo sysctl --system. Этот шаг не требуется в Debian 11. -
Рекомендуется установить
fuse-overlayfs. Выполнитеsudo apt-get install -y fuse-overlayfs. Использование драйвера хранилищаoverlay2со специфичной для Debian опциейsudo modprobe overlay permit_mounts_in_userns=1также возможно, однако крайне не рекомендуется из-за нестабильности. -
Rootless docker требует версию
slirp4netnsвышеv0.4.0(когдаvpnkitне установлен). Проверьте, есть ли у вас это с$ slirp4netns --version
Если у вас его нет, скачайте и установите с помощьюsudo apt-get install -y slirp4netnsили скачайте последнюю версию.
Arch Linux.
-
Рекомендуется установить
fuse-overlayfs. Выполнитеsudo pacman -S fuse-overlayfs. -
Добавьте
kernel.unprivileged_userns_clone=1в/etc/sysctl.conf(или/etc/sysctl.d) и запуститеsudo sysctl --system
OpenSUSE и SLES.
-
Рекомендуется установить
fuse-overlayfs. Выполнитеsudo zypper install -y fuse-overlayfs. -
Требуется
sudo modprobe ip_tables iptable_mangle iptable_nat iptable_filter. Это может потребоваться и в других дистрибутивах в зависимости от конфигурации. -
Известно, что работает на openSUSE 15 и SLES 15.
CentOS 8, RHEL 8 и Fedora.
-
Рекомендуется установить
fuse-overlayfs. Выполнитеsudo dnf install -y fuse-overlayfs. -
Возможно, вам понадобится
sudo dnf install -y iptables. -
Известно, что он работает на CentOS 8, RHEL 8, и Fedora 34.
CentOS 7 и RHEL 7.
-
Add
user.max_user_namespaces=28633to/etc/sysctl.conf(or/etc/sysctl.d) and runsudo sysctl --system. -
systemctl --userпо умолчанию не работает. Запуститеdockerd-rootless.shнапрямую без systemd.
Известные ограничения.
- Поддерживаются только следующие драйверы устройств хранения:
overlay2(только если работа с ядром 5.11 или более поздней версии, или Ubuntu-подобным ядром)fuse-overlayfs(только если работает с ядром 4.18 или более поздней версии, и установлен fuse-overlayfs)btrfs(только если работа с ядром 4.18 или более поздней версии, или~/.local/share/dockerсмонтирована с опциейuser_subvol_rm_allowed mount)vfs
- Cgroup поддерживается только при запуске cgroup v2 и systemd. См. Ограничение ресурсов.
- Следующие функции не поддерживаются:
- AppArmor
- Контрольная точка
- Оверлейная сеть
- Предоставление портов SCTP
- Чтобы использовать команду
pingсм. раздел Маршрутизация пакетов ping. - Для выявления привилегированных портов TCP/UDP (< 1024), см. раздел Выявление привилегированных портов.
IPAddress, отображаемый вdocker inspectи имеющий пространство имен внутри сетевого пространства имен RootlessKit. Это означает, что IP-адрес недостижим с хоста безnsenter-регистрации в сетевом пространстве имен.- Хост-сеть (
docker run --net=host) также находится в пространстве имен внутри RootlessKit. - Монтирование NFS в качестве "data-root" docker не поддерживается. Это ограничение не является специфическим для режима rootless.
Установка.
Note.
Если демон Docker уже запущен, рассмотрите возможность его отключения.
$ sudo systemctl disable --now docker.service docker.socket
С пакетами (RPM/DEB).
Если вы установили Docker 20.10 или более поздней версии с пакетами RPM/DEB, то вам следует иметь dockerd-rootless-setuptool.sh в /usr/bin.
Запустите dockerd-rootless-setuptool.sh install от имени пользователя без права root для настройки демона:
$ dockerd-rootless-setuptool.sh install [INFO] Creating /home/testuser/.config/systemd/user/docker.service ... export PATH=/usr/bin:$PATH export DOCKER_HOST=unix:///run/user/1000/docker.sock
Если dockerd-rootless-setuptool.sh отсутствует, вам может потребоваться установить пакет docker-ce-rootless-extras вручную, например,
$ sudo apt-get install -y docker-ce-rootless-extras
Без пакетов.
Если у вас нет разрешения на запуск таких менеджеров пакетов, как apt-get и dnf, воспользуйтесь сценарием установки, доступным по адресу https://get.docker.com/rootless. Поскольку статические пакеты недоступны для s390x, следовательно, они не поддерживаются для s390x.
curl -fsSL https://get.docker.com/rootless | sh ... [INFO] Creating /home/testuser/.config/systemd/user/docker.service ... [INFO] Installed docker.service successfully. [INFO] To control docker.service, run: `systemctl --user (start|stop|restart) docker.service` [INFO] To run docker.service on system startup, run: `sudo loginctl enable-linger testuser` [INFO] Make sure the following environment variables are set (or add them to ~/.bashrc): export PATH=/home/testuser/bin:$PATH export DOCKER_HOST=unix:///run/user/1000/docker.sock
Двоичные файлы будут установлены в ~/bin.
Если вы столкнулись с ошибкой, см. раздел Устранение неполадок.
Удаление.
Чтобы удалить системную службу демона Docker, запустите dockerd-rootless-setuptool.sh uninstall:
$ dockerd-rootless-setuptool.sh uninstall + systemctl --user stop docker.service + systemctl --user disable docker.service Removed /home/testuser/.config/systemd/user/default.target.wants/docker.service. [INFO] Uninstalled docker.service [INFO] This uninstallation tool does NOT remove Docker binaries and data. [INFO] To remove data, run: `/usr/bin/rootlesskit rm -rf /home/testuser/.local/share/docker`
Удалите переменные среды PATH и DOCKER_HOST, если вы добавили их в ~/.bashrc.
Для удаления каталога данных запустите rootlesskit rm -rf ~/.local/share/docker.
Чтобы удалить двоичные файлы, удалите пакет docker-ce-rootless-extras , если вы установили Docker с помощью менеджеров пакетов. Если вы установили Docker с помощью https://get.docker.com/rootless (Установить без пакетов), удалите двоичные файлы в каталоге ~/bin:
$ cd ~/bin $ rm -f containerd containerd-shim containerd-shim-runc-v2 ctr docker docker-init docker-proxy dockerd dockerd-rootless-setuptool.sh dockerd-rootless.sh rootlesskit rootlesskit-docker-proxy runc vpnkit
Использование.
Демон.
С systemd (Настоятельно рекомендуется).
Файл блока systemd устанавливается в ~/.config/systemd/user/docker.service.
Используйте systemctl --user для управления жизненным циклом демона:
$ systemctl --user start docker
Чтобы запустить демон при запуске системы, включите службу systemd и lingering:
$ systemctl --user enable docker $ sudo loginctl enable-linger $(whoami)
Запуск Rootless Docker как общесистемного сервиса (/etc/systemd/system/docker.service) не поддерживается, даже с директивой User= .
Без systemd.
Чтобы запустить демон напрямую без systemd, нужно запустить dockerd-rootless.sh вместо dockerd.
Необходимо установить следующие переменные среды:
$HOME: домашний каталог$XDG_RUNTIME_DIR: эфемерный каталог, доступный только ожидаемому пользователю, например,~/.docker/run. Каталог должен удаляться при каждом завершении работы узла. Каталог может находиться на tmpfs, однако не должен находиться в/tmp. Расположение этого каталога в каталоге/tmpможет быть уязвимым для атаки TOCTOU.
Замечания о путях к каталогам:
- По умолчанию путь к сокету установлен в
$XDG_RUNTIME_DIR/docker.sock.$XDG_RUNTIME_DIRобычно устанавливается в/run/user/$UID. - По умолчанию для каталога данных задано значение
~/.local/share/docker. Каталог данных не должен находиться в NFS. - По умолчанию для каталога конфигурации демона установлено значение
~/.config/docker. Этот каталог отличается от~/.docker, используемого клиентом.
Клиент.
Необходимо явно указать путь к сокету или контекст CLI.
Чтобы указать путь к сокету с помощью $DOCKER_HOST:
$ export DOCKER_HOST=unix://$XDG_RUNTIME_DIR/docker.sock $ docker run -d -p 8080:80 nginx
Чтобы задать контекст CLI с помощью docker context:
$ docker context use rootless rootless Current context is now "rootless" $ docker run -d -p 8080:80 nginx
Рекомендации.
Rootless Docker в Docker.
Чтобы запустить "внекорневой" Docker внутри "корневого" Docker, используйте образ docker:<version>-dind-rootless вместо docker:<version>-dind.
$ docker run -d --name dind-rootless --privileged docker:20.10-dind-rootless
Образ docker:<version>-dind-rootless запускается от имени пользователя без рута (UID 1000). Однако --privileged требуется для отключения seccomp, AppArmor и масок монтирования.
Открытие сокета Docker API через TCP.
Чтобы открыть сокет Docker API через TCP, необходимо запустить dockerd-rootless.sh с DOCKERD_ROOTLESS_ROOTLESSKIT_FLAGS="-p 0.0.0.0:2376:2376/tcp".
$ DOCKERD_ROOTLESS_ROOTLESSKIT_FLAGS="-p 0.0.0.0:2376:2376/tcp" \ dockerd-rootless.sh \ -H tcp://0.0.0.0:2376 \ --tlsverify --tlscacert=ca.pem --tlscert=cert.pem --tlskey=key.pem
Предоставление доступа к сокету DOCKER API через SSH.
Чтобы открыть сокет Docker API через SSH, необходимо убедиться, что на удаленном хосте установлен $DOCKER_HOST.
$ ssh -l <REMOTEUSER> <REMOTEHOST> 'echo $DOCKER_HOST' unix:///run/user/1001/docker.sock $ docker -H ssh://<REMOTEUSER>@<REMOTEHOST> run ...
Маршрутизация пинг-пакетов.
В некоторых дистрибутивах ping не работает по умолчанию.
Add net.ipv4.ping_group_range = 0 2147483647 to /etc/sysctl.conf (or /etc/sysctl.d) and run sudo sysctl --system to allow using ping.
Exposing privileged ports
To expose privileged ports (< 1024), set CAP_NET_BIND_SERVICE on rootlesskit binary.
$ sudo setcap cap_net_bind_service=ep $HOME/bin/rootlesskit
Or add net.ipv4.ip_unprivileged_port_start=0 to /etc/sysctl.conf (or /etc/sysctl.d) and run sudo sysctl --system.
Limiting resources
Limiting resources with cgroup-related docker run flags such as --cpus, --memory, --pids-limit is supported only when running with cgroup v2 and systemd. See Changing cgroup version to enable cgroup v2.
If docker info shows none as Cgroup Driver, the conditions are not satisfied. When these conditions are not satisfied, rootless mode ignores the cgroup-related docker run flags. See Limiting resources without cgroup for workarounds.
If docker info shows systemd as Cgroup Driver, the conditions are satisfied. However, typically, only memory and pids controllers are delegated to non-root users by default.
$ cat /sys/fs/cgroup/user.slice/user-$(id -u).slice/user@$(id -u).service/cgroup.controllers memory pids
To allow delegation of all controllers, you need to change the systemd configuration as follows:
# mkdir -p /etc/systemd/system/user@.service.d # cat > /etc/systemd/system/user@.service.d/delegate.conf << EOF [Service] Delegate=cpu cpuset io memory pids EOF # systemctl daemon-reload
Note
Delegating
cpusetrequires systemd 244 or later.
Limiting resources without cgroup
Even when cgroup is not available, you can still use the traditional ulimit and cpulimit, though they work in process-granularity rather than in container-granularity, and can be arbitrarily disabled by the container process.
For example:
- To limit CPU usage to 0.5 cores (similar to
docker run --cpus 0.5):docker run <IMAGE> cpulimit --limit=50 --include-children <COMMAND> -
To limit max VSZ to 64MiB (similar to
docker run --memory 64m):docker run <IMAGE> sh -c "ulimit -v 65536; <COMMAND>" - To limit max number of processes to 100 per namespaced UID 2000 (similar to
docker run --pids-limit=100):docker run --user 2000 --ulimit nproc=100 <IMAGE> <COMMAND>
Troubleshooting
Errors when starting the Docker daemon
[rootlesskit:parent] error: failed to start the child: fork/exec /proc/self/exe: operation not permitted
This error occurs mostly when the value of /proc/sys/kernel/unprivileged_userns_clone is set to 0:
$ cat /proc/sys/kernel/unprivileged_userns_clone 0
To fix this issue, add kernel.unprivileged_userns_clone=1 to /etc/sysctl.conf (or /etc/sysctl.d) and run sudo sysctl --system.
[rootlesskit:parent] error: failed to start the child: fork/exec /proc/self/exe: no space left on device
This error occurs mostly when the value of /proc/sys/user/max_user_namespaces is too small:
$ cat /proc/sys/user/max_user_namespaces 0
To fix this issue, add user.max_user_namespaces=28633 to /etc/sysctl.conf (or /etc/sysctl.d) and run sudo sysctl --system.
[rootlesskit:parent] error: failed to setup UID/GID map: failed to compute uid/gid map: No subuid ranges found for user 1001 (“testuser”)
This error occurs when /etc/subuid and /etc/subgid are not configured. See Prerequisites.
could not get XDG_RUNTIME_DIR
This error occurs when $XDG_RUNTIME_DIR is not set.
On a non-systemd host, you need to create a directory and then set the path:
$ export XDG_RUNTIME_DIR=$HOME/.docker/xrd $ rm -rf $XDG_RUNTIME_DIR $ mkdir -p $XDG_RUNTIME_DIR $ dockerd-rootless.sh
Note: You must remove the directory every time you log out.
On a systemd host, log into the host using pam_systemd (see below). The value is automatically set to /run/user/$UID and cleaned up on every logout.
systemctl --user fails with “Failed to connect to bus: No such file or directory”
This error occurs mostly when you switch from the root user to an non-root user with sudo:
$ sudo -iu testuser $ systemctl --user start docker Failed to connect to bus: No such file or directory
Instead of sudo -iu <USERNAME>, you need to log in using pam_systemd. For example:
- Log in through the graphic console
ssh <USERNAME>@localhostmachinectl shell <USERNAME>@
The daemon does not start up automatically
You need sudo loginctl enable-linger $(whoami) to enable the daemon to start up automatically. See Usage.
iptables failed: iptables -t nat -N DOCKER: Fatal: can’t open lock file /run/xtables.lock: Permission denied
This error may happen with an older version of Docker when SELinux is enabled on the host.
The issue has been fixed in Docker 20.10.8. A known workaround for older version of Docker is to run the following commands to disable SELinux for iptables:
$ sudo dnf install -y policycoreutils-python-utils && sudo semanage permissive -a iptables_t
docker pull errors
docker: failed to register layer: Error processing tar file(exit status 1): lchown <FILE>: invalid argument
This error occurs when the number of available entries in /etc/subuid or /etc/subgid is not sufficient. The number of entries required vary across images. However, 65,536 entries are sufficient for most images. See Prerequisites.
docker: failed to register layer: ApplyLayer exit status 1 stdout: stderr: lchown <FILE>: operation not permitted
This error occurs mostly when ~/.local/share/docker is located on NFS.
A workaround is to specify non-NFS data-root directory in ~/.config/docker/daemon.json as follows:
{"data-root":"/somewhere-out-of-nfs"}
docker run errors
docker: Error response from daemon: OCI runtime create failed: ...: read unix @->/run/systemd/private: read: connection reset by peer: unknown.
This error occurs on cgroup v2 hosts mostly when the dbus daemon is not running for the user.
$ systemctl --user is-active dbus
inactive
$ docker run hello-world
docker: Error response from daemon: OCI runtime create failed: container_linux.go:380: starting container process caused: process_linux.go:385: applying cgroup configuration for process caused: error while starting unit "docker
-931c15729b5a968ce803784d04c7421f791d87e5ca1891f34387bb9f694c488e.scope" with properties [{Name:Description Value:"libcontainer container 931c15729b5a968ce803784d04c7421f791d87e5ca1891f34387bb9f694c488e"} {Name:Slice Value:"use
r.slice"} {Name:PIDs Value:@au [4529]} {Name:Delegate Value:true} {Name:MemoryAccounting Value:true} {Name:CPUAccounting Value:true} {Name:IOAccounting Value:true} {Name:TasksAccounting Value:true} {Name:DefaultDependencies Val
ue:false}]: read unix @->/run/systemd/private: read: connection reset by peer: unknown.
To fix the issue, run sudo apt-get install -y dbus-user-session or sudo dnf install -y dbus-daemon, and then relogin.
If the error still occurs, try running systemctl --user enable --now dbus (without sudo).
--cpus, --memory, and --pids-limit are ignored
This is an expected behavior on cgroup v1 mode. To use these flags, the host needs to be configured for enabling cgroup v2. For more information, see Limiting resources.
Networking errors
docker run -p fails with cannot expose privileged port
docker run -p fails with this error when a privileged port (< 1024) is specified as the host port.
$ docker run -p 80:80 nginx:alpine docker: Error response from daemon: driver failed programming external connectivity on endpoint focused_swanson (9e2e139a9d8fc92b37c36edfa6214a6e986fa2028c0cc359812f685173fa6df7): Error starting userland proxy: error while calling PortManager.AddPort(): cannot expose privileged port 80, you might need to add "net.ipv4.ip_unprivileged_port_start=0" (currently 1024) to /etc/sysctl.conf, or set CAP_NET_BIND_SERVICE on rootlesskit binary, or choose a larger port number (>
When you experience this error, consider using an unprivileged port instead. For example, 8080 instead of 80.
docker run -p 8080:80 nginx:alpine
To allow exposing privileged ports, see Exposing privileged ports.
ping doesn’t work
Ping does not work when /proc/sys/net/ipv4/ping_group_range is set to 1 0:
cat /proc/sys/net/ipv4/ping_group_range 1 0
For details, see Routing ping packets.
IPAddress shown in docker inspect is unreachable
This is an expected behavior, as the daemon is namespaced inside RootlessKit’s network namespace. Use docker run -p instead.
--net=host doesn’t listen ports on the host network namespace
This is an expected behavior, as the daemon is namespaced inside RootlessKit’s network namespace. Use docker run -p instead.
Network is slow
Docker with rootless mode uses slirp4netns as the default network stack if slirp4netns v0.4.0 or later is installed. If slirp4netns is not installed, Docker falls back to VPNKit.
Installing slirp4netns may improve the network throughput. See RootlessKit documentation for the benchmark result.
Also, changing MTU value may improve the throughput. The MTU value can be specified by creating ~/.config/systemd/user/docker.service.d/override.conf with the following content:
[Service] Environment="DOCKERD_ROOTLESS_ROOTLESSKIT_MTU=<INTEGER>"
And then restart the daemon:
$ systemctl --user daemon-reload $ systemctl --user restart docker
docker run -p does not propagate source IP addresses
This is because Docker with rootless mode uses RootlessKit’s builtin port driver by default.
The source IP addresses can be propagated by creating ~/.config/systemd/user/docker.service.d/override.conf with the following content:
[Service] Environment="DOCKERD_ROOTLESS_ROOTLESSKIT_PORT_DRIVER=slirp4netns"
And then restart the daemon:
$ systemctl --user daemon-reload $ systemctl --user restart docker
Note that this configuration decreases throughput. See RootlessKit documentation for the benchmark result.
Tips for debugging
Entering into dockerd namespaces
The dockerd-rootless.sh script executes dockerd in its own user, mount, and network namespaces.
For debugging, you can enter the namespaces by running nsenter -U --preserve-credentials -n -m -t $(cat $XDG_RUNTIME_DIR/docker.pid).