How to fix Docker error: Got permission denied while trying to connect to the Docker daemon socket

How to fix Docker error: Got permission denied while trying to connect to the Docker daemon socket

I freshly installed docker on my system, tried to build a docker image and got stuck on the following error:

$ 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.39/containers/create: dial unix /var/run/docker.sock: connect: permission denied.
See 'docker run --help'.

I was stumped because the installation guide I was following didn't mention anything of this sort. Turns out, as a non-root user, we have to create a docker group and add our user:

  • Create a docker group
sudo groupadd docker
  • Add your user to the docker group.
sudo usermod -aG docker ${USER}
  • On Linux, run the following command to activate the changes to groups
newgrp docker

NOTE: If testing on a virtual machine, a restart might be needed for the changes to take place.

  • Validate that the docker group changes got applied and we can run docker run without sudo
$ docker run hello-world

WARNING: Error loading config file: /home/ndatta/.docker/config.json: EOF
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
b8dfde127a29: Pull complete
Digest: sha256:9f6ad537c5132bcce57f7a0a20e317228d382c3cd61edae14650eec68b2b345c
Status: Downloaded newer image for hello-world:latest

Reference: docs.docker.com/engine/install/linux-postin..