0

I want to run my docker by running this command:

docker build -t getting-started .

I get the following error:

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/build?buildargs=%7B%7D&cachefrom=%5B%5D&cgroupparent=&cpuperiod=0&cpuquota=0&cpusetcpus=&cpusetmems=&cpushares=0&dockerfile=Dockerfile&labels=%7B%7D&memory=0&memswap=0&networkmode=default&rm=1&shmsize=0&t=getting-started&target=&ulimits=null&version=1: dial unix /var/run/docker.sock: connect: permission denied

My question is: how can I run docker on ubuntu without adding "sudo"?

ErikMD
  • 13,377
  • 3
  • 35
  • 71
  • Thanks @BMitch for having found that duplicate! But it seems the answer I proposed here was not mentioned at all in the duplicate thread. Would you have some advice about this? (e.g., to cross-post my answer there? or just do nothing :) – ErikMD Jan 29 '21 at 13:40
  • 1
    @ErikMD if your answer applies there, then I'd post it there. I don't see an issue having a duplicate answer posted when only one of the questions is still open. – BMitch Jan 29 '21 at 14:21
  • OK done, thanks @BMitch :) – ErikMD Jan 29 '21 at 15:10

2 Answers2

2

TL;DR: Unlike what many tutorials on the web propose (add your user account to the docker group, which is risky! see below), you could just add an alias in your .bashrc to avoid typing sudo, while having the "password prompt protection".

To be more precise: the Docker daemon socket is owned by root:docker:

$ ls -l /var/run/docker.sock
srw-rw---- 1 root docker 0 janv. 28 14:23 /var/run/docker.sock

so with this default setup, you need to prepend all docker CLI commands by sudo.

To avoid this, you can either:

  1. Add $USER to the docker group (but that's quite risky to do this on your personal workstation, as this would amount to provide your user account with root permissions without any sudo password prompt nor auditing).

    See also this page in the official Docker documentation:
    https://docs.docker.com/engine/security/#docker-daemon-attack-surface

  2. Or, to prepend sudo automatically but avoid typing sudo docker manually, a good practice consists in adding the following alias in your ~/.bashrc file (see e.g. this thread for details):

    __docker() {
        if [[ "${BASH_SOURCE[*]}" =~ "bash-completion" ]]; then
            docker "$@"
        else
            sudo docker "$@"
        fi
    }
    alias docker=__docker
    

    Then you can test this by opening a new terminal and typing:

    $ docker run --rm -it debian:10  # asks your password
    $ \docker run --help  # does not ask your password thanks to '\'
    
ErikMD
  • 13,377
  • 3
  • 35
  • 71
1

You should add user to docker group:

sudo usermod -aG docker $USER

After you may have to restart Ubuntu

Serge K
  • 615
  • 3
  • 11