How To Run Docker Commands Without Sudo

How To Run Docker Commands Without Sudo

When Docker is installed on a machine, its daemon binds with the Unix socket making its commands usable through the root user or a sudoer. The root user can run the docker commands directly while the sudoer has to use sudo with the docker commands, for example, sudo docker ps -a.

This behavior stems from the fact that the Unix socket is owned by the Root user and for any command to be used by a non-root user, it has to be with the sudo command. Due to security reasons, we need to create an admin sudo user to run commands in place of the root, however, it may become frustrating having to type sudo with every other docker command.

Creating a docker user

Recall that for a user to run commands as the root, they must use the sudo command. The sudoer group on a Linux machine enables users to connect to the Unix socket. In the same way, the docker daemon that is bound to the Unix socket can be used by a docker group.

Some Linux distributions already come with the docker group automatically after installation while others do not. In this case, you will have to create the group as follows:

sudo groupadd docker

And just as users are added to the sudo group to make them run commands with it, you will have to add the user to the docker group like this:

sudo usermod -aG docker $USER

Note that the user you are doing this for is a non-root user. This means that the user is not in the sudo group. If you don't have a non-root user, you should create one first before adding it to the docker group. You can reboot your system or restart the docker daemon to effect the changes you made.

To confirm all you have done, switch to the new docker user's home directory and type:

docker version

You should get an output without any error.

Conclusion

And that's it on how you can run docker commands without using the sudo command. Thank you.