docker.sock permission denied

When I try to run simple docker commands like:

$ docker ps -a

I get an error message:

Got permission denied ... /var/run/docker.sock: connect: permission denied

When I check permissions with

$ ls -al /var/run/

I see this line:

srw-rw---- root docker docker.sock

So, I follow an advice from many forums and add local user to docker group:

$ sudo usermod -aG docker $USER

But it does not help. I still get the very same error message. How can I fix it?


Solution 1:

For those new to the shell, the command:

$ sudo usermod -aG docker $USER

needs to have $USER defined in your shell. This is often there by default, but you may need to set the value to your login id in some shells.


Changing the groups of a user does not change existing logins, terminals, and shells that a user has open. To avoid performing a login again, you can simply run:

$ newgrp docker

to get access to that group in your current shell.


Once you have done this, the user effectively has root access on the server, so only do this for users that are trusted with unrestricted sudo access.

Solution 2:

Reason: The error message means that the current user can’t access the docker engine, because the user hasn't enough permissions to access the UNIX socket to communicate with the engine.

Quick Fix:

  1. Run the command as root using sudo.

    sudo docker ps
    
  2. Change the permissions of /var/run/docker.sock for the current user.

    sudo chown $USER /var/run/docker.sock
    

Caution: Running sudo chmod 777 /var/run/docker.sock will solve your problem but it will open the docker socket for everyone which is a security vulnerability as pointed out by @AaylaSecura. Hence it shouldn't be used, except for testing purposes on the local system.

Permanent Solution:

Add the current user to the docker group.

sudo usermod -a -G docker $USER

Note: You have to log out and log in again for the changes to take effect.

Refer to this blog to know more about managing Docker as a non-root user.

Solution 3:

  1. Make sure your $USER variable is set

    $ echo $USER
    
    $ sudo usermod -aG docker $USER
    
  2. logout

  3. Upon login, restart the docker service

    $ sudo systemctl restart docker
    
    $ docker ps