- How can I use Docker without sudo?
- 5 Answers 5
- Linux post-installation steps for Docker Engine
- Manage Docker as a non-root user
- Configure Docker to start on boot with systemd
- Configure default logging driver
- Next steps
- Running Docker Without sudo
- 1. Introduction
- 2. Linux sudo Command
- 3. Linux Groups and Users
- 3.1. Adding Users to Linux Groups
- 4. Conclusion
- Добавление пользователя в группу docker.
How can I use Docker without sudo?
Recommended installation is not the docker in default ubuntu repos; instead, instructions here ( docs.docker.com/engine/installation/linux/ubuntulinux ), recommend using the docker repo. Remove all the existing docker stuff, and verify you’re getting the one from the right source: apt-cache policy docker-engine (apt url should be from dockerproject.org)
How about an alias:? That way, you still use sudo, with password protection. alias docker=»sudo docker «
What junk is this for requiring root to do simple things such as docker info . Like docker info needs raw access to all my file and devices and ports to run.
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.
- cgroups resource controls, apparmor security profiles, checkpoint/restore, overlay networks etc. do not work on rootless mode.
- Exposing ports from containers currently requires manual socat helper process.
- Only Ubuntu-based distros support overlay filesystems in rootless mode.
- Rootless mode is currently only provided for nightly builds that may not be as stable as you are used to.
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.
Starting in version 0.5.3, if you (or your Docker installer) create a Unix group called docker and add users to it, then the docker daemon will make the ownership of the Unix socket read/writable by the docker group when the daemon starts. The docker daemon must always run as the root user, but if you run the docker client as a user in the docker group then you don’t need to add sudo to all the client commands. As of 0.9.0, you can specify that a group other than docker should own the Unix socket with the -G option.
Warning: The docker group (or the group specified with -G) is root-equivalent; see Docker Daemon Attack Surface details and this blogpost on Why we don’t let non-root users run Docker in CentOS, Fedora, or RHEL (thanks michael-n).
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.
$ dockerd-rootless.sh --experimental
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.
sudo gpasswd -a $USER docker
Linux post-installation steps for Docker Engine
These optional post-installation procedures shows you how to configure your Linux host machine to work better with Docker.
Manage Docker as a non-root user
The Docker daemon binds to a Unix socket, not a TCP port. By default it’s the root user that owns the Unix socket, and other users can only access it using sudo . The Docker daemon always runs as the root user.
If you don’t want to preface the docker command with sudo , create a Unix group called docker and add users to it. When the Docker daemon starts, it creates a Unix socket accessible by members of the docker group. On some Linux distributions, the system automatically creates this group when installing Docker Engine using a package manager. In that case, there is no need for you to manually create the group.
Warning
The docker group grants root-level privileges to the 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:
$ sudo usermod -aG docker $USER
If you’re running Linux in a virtual machine, it may be necessary to restart the virtual machine for changes to take effect.
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:
WARNING: Error loading config file: /home/user/.docker/config.json - stat /home/user/.docker/config.json: permission denied
This error indicates that the permission settings for the ~/.docker/ directory are incorrect, due to having used the sudo command earlier. To fix this problem, either remove the ~/.docker/ directory (it’s recreated automatically, but any custom settings are lost), or change its ownership and permissions using the following commands:
$ sudo chown "$USER":"$USER" /home/"$USER"/.docker -R $ sudo chmod g+rwx "$HOME/.docker" -R
Configure Docker to start on boot with systemd
Many modern Linux distributions use systemd to manage which services start when the system boots. On Debian and Ubuntu, the Docker service starts on boot by default. To automatically start Docker and containerd on boot for other Linux distributions using systemd, run the following commands:
$ sudo systemctl enable docker.service $ sudo systemctl enable containerd.service
To stop this behavior, use disable instead.
$ sudo systemctl disable docker.service $ sudo systemctl disable containerd.service
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.
Configure default logging driver
Docker provides logging drivers for collecting and viewing log data from all containers running on a host. The default logging driver, json-file , writes log data to JSON-formatted files on the host filesystem. Over time, these log files expand in size, leading to potential exhaustion of disk resources.
To avoid issues with overusing disk for log data, consider one of the following options:
- Configure the json-file logging driver to turn on log rotation.
- Use an alternative logging driver such as the “local” logging driver that performs log rotation by default.
- Use a logging driver that sends logs to a remote logging aggregator.
Next steps
- Read the Get started training modules to learn how to build an image and run it as a containerized application.
- Review the topics in Develop with Docker to learn how to build new applications using Docker.
Running Docker Without sudo
The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.
To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.
Connect your cluster and start monitoring your K8s costs right away:
1. Introduction
Running Docker commands with sudo ensures that the Docker command is executed with the security rights of root (by using sudo ) or by a user who is a member of the docker group.
However, we get an error message when we try running Docker commands without the sudo :
$ docker run hello-world docker: Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Post "http://%2Fvar%2Frun%2Fdocker.sock/v1.24/containers/create": dial unix /var/run/docker.sock: connect: permission denied. See 'docker run --help'.
In this quick tutorial, we’ll learn how to run Docker commands without sudo.
2. Linux sudo Command
In Linux, we can run a command as a superuser by prefixing the command with sudo . sudo stands for “Super User Do.”
By prefixing any command with sudo , the system executes the command with administrative rights. Users that want to use the sudo command need to have an entry in the /etc/sudoers file found in the system directory.
3. Linux Groups and Users
Linux enables several users to log in simultaneously and operate the system without interference. A user’s default group is its primary group, as specified in the Linux system’s /etc/passwd file.
Docker is a free and open platform for building, delivering, and operating apps. Docker allows us to bundle and run an application in a container, which is a loosely isolated environment. Continuous Integration and Delivery (CI/CD) procedures benefit greatly from containers.
To get information about a user sally, we can use the id command:
$ id sally uid=1000(sally) gid=1001(example_group) groups=1001(example_group),27(sudo)
After creating users in primary groups, we can associate these users with secondary groups. Linux systems store their groups in the /etc/group file.
To find the group(s) sally belongs to, we can run:
$ groups sally user: group sudo
We can add varying levels of permissions to a group, and all members of the same group share the group’s permissions.
3.1. Adding Users to Linux Groups
Let’s add our user sally to a secondary group called myuser:
$ sudo usermod -aG myuser sally
In the same vein, to run Docker commands without the prefix sudo, we’d create a Unix group called docker and then add our user sally to the docker group:
$ sudo groupadd docker $ sudo usermod -aG docker sally $ su - sally
To make these changes effective, we’ll log out and log back in. This action will allow the system to re-evaluate our group membership.
When testing on a virtual machine, it may be necessary to restart the virtual machine for changes to take effect. We try our permission by running Docker commands:
$ docker run hello-world latest: Pulling from library/hello-world 2db29710123e: Pull complete Digest: sha256:80f3 Status: Downloaded newer image for hello-world:latest ……………………………………
We can now run Docker commands without sudo .
4. Conclusion
In conclusion, we can execute Docker commands with full administrative privileges and security. The Docker daemon binds to a Unix socket, and the root user owns this Unix socket. Other users need to prefix their docker commands with sudo to access the Docker daemon.
By adding our Linux username to the Unix group docker , we can bypass this. When the Docker daemon starts, it creates a Unix socket accessible by the members of the docker group.
Running Docker commands with the sudo command is a sound security restriction. However, users added to the Unix group docker can run Docker commands as root users while maintaining their usernames.
Adding users to groups is also helpful in granting access to other users of our Linux machine, as groups help allow multiple independent users’ accounts to collaborate and share files.
Добавление пользователя в группу docker.
После установки пакета docker в операционных системах Linux, если попробовать вызвать любую команду docker без sudo то возникнет ошибка:
Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Get http://%2Fvar%2Frun%2Fdocker.sock/v1.40/containers/json: dial unix /var/run/docker.sock: connect: permission denied
Далее в терминальных командах будет использоваться $ , в случае если вам будет нужно в группу docker добавить пользователя, под которым вы не работаете, то замените на имя нужного пользователя.
При локальной разработке в Linux, чтобы постоянно не запускать команды docker с правами root , можно добавить пользователя в группу docker.
Сделать это очень просто с помощью команды:
Команда отрабатывает без вывода успеха в консоль. И теперь, чтобы изменения вступили в силу нужно либо выйти и снова залогиниться на удаленный сервер, или в случае локальной «машины», достаточно выполнить команду:
Потребуется ввести пароль пользователя и вы получите новую сессию для пользователя.
Теперь если посмотреть в каких группах состоит текущий пользователь, то появится группа 998(docker) . Для этого достаточно выполнить команду: