Home > database >  Connect to docker socket from within container
Connect to docker socket from within container

Time:10-21

I'm running a docker-compose setup via Laravel Sail where I'd like to access the docker socket from within the container.

I've added the /var/run/docker.sock socket to the volumes but when I try to access the socket through curl it replies with curl: (7) Couldn't connect to server:

$ curl --unix-socket /var/run/docker.sock http://localhost/version

reply: curl: (7) Couldn't connect to server

This is part of my docker-compose.yml file:

services:
    laravel.test:
        volumes:
            - '.:/var/www/html'
            - /var/run/docker.sock:/var/run/docker.sock

What am I doing wrong here?

Thanks in advance!

CodePudding user response:

Basically you're trying to access an Unix socket owned by root, as it's /var/run/docker.sock with a different user than root.

Only thing you should do is to create a group docker in the image you want to use and to add the user of the image to that group, since the Socket is also owned by the docker group.

srw-rw----  1 root  docker     0 Jul 29 07:51 docker.sock

Dockerfile

DO NOT USE THIS, AS @David Maze COMENTED THE GID OF THE CREATED DOCKER GROUP COULD NOT MATCH THE GID FROM THE HOST.

FROM ...

USER root
RUN groupadd docker
RUN usermod -aG docker sail

USER sail
...

Docker Compose v3

Docker Compose on its format version v2 had the possibility of including group_add but that's not an option anymore in v3.

Even if you could jut use the version 2 of the compose, there's an option of doing it with the v3.

services:
    laravel.test:
        user: "sail:${GIP}"
        volumes:
            - '.:/var/www/html'
            - /var/run/docker.sock:/var/run/docker.sock

When you're going to start your containers with docker-compose up -d, export first the group ID for the docker group in your host machine.

export GIP=$(cut -d: -f3 < <(getent group docker))
docker-compose up -d

Then your sail user will have access to /var/run/docker.sock and to all the Docker CLI commands.

Also, keep in mind that the docker group grants privileges equivalent to the root user. Take a look on Docker Daemon Attack Surface to be conscious about the security impact that could have in your system.

  • Related