Search code examples
dockercontinuous-integrationsudocircleci

Docker: permission denied while trying to connect to Docker Daemon with local CircleCI build


I have a very simple config.yml:

version: 2

jobs:
  build:
    working_directory: ~/app
    docker:
      - image: circleci/node:8.4.0
    steps:
      - checkout
      - run: node -e "console.log('Hello from NodeJS ' + process.version + '\!')"
      - run: yarn
      - setup_remote_docker
      - run: docker build .

All it does: boot a node image, test if node is running, do a yarn install and a docker build.

My dockerfile is nothing special; it has a COPY and ENTRYPOINT.

When I run circleci build on my MacBook Air using Docker Native, I get the following error:

Got permission denied while trying to connect to the Docker daemon socket at unix://[...]

If I change the docker build . command to: sudo docker build ., everything works as planned, locally, with circleci build.
However, pushing this change to CircleCI will result in an error: Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?

So, to summarize: using sudo works, locally, but not on CircleCI itself. Not using sudo works on CircleCI, but not locally.

Is this something the CircleCI staff has to fix, or is there something I can do?

For reference, I have posted this question on the CircleCI forums as well.


Solution

  • I've created a workaround for myself.

    In the very first step of the config.yml, I run this command:

    if [[ $CIRCLE_SHELL_ENV == *"localbuild"* ]]; then
      echo "This is a local build. Enabling sudo for docker"
      echo sudo > ~/sudo
    else
      echo "This is not a local build. Disabling sudo for docker"
      touch ~/sudo
    fi
    

    Afterwards, you can do this:

    eval `cat ~/sudo` docker build .
    

    Explanation:

    The first snippet checks if the CircleCI-provided environment variable CIRCLE_SHELL_ENV contains localbuild. This is only true when running circleci build on your local machine. If true, it creates a file called sudo with contents sudo in the home directory. If false, it creates a file called sudo with NO contents in the home directory.

    The second snippet opens the ~/sudo file, and executes it with the arguments you give afterwards. If the ~/sudo file contains "sudo", the command in this example will become sudo docker build ., if it doesn't contain anything, it will become docker build ., with a space before it, but that will be ignored.

    This way, both the local (circleci build) builds and remote builds will work.