dockersocketsjenkinsjenkins-agent

Access docker within container on jenkins slave


my question is basically a combination of Access Docker socket within container and Accessing docker host from (jenkins) docker container

My goal

to run Jenkins fully dockerized including dynamic slaves and being able to create docker-containers within the slaves.

Except for the last part everything is already working thanks to https://github.com/maxfields2000/dockerjenkins_tutorial if the Unix-docker-sock is properly exposed to the Jenkins master.

The problem

unlike the slaves which are provisioned dynamically, the master is started via docker-compose and thus has proper access to the UNIX socket.

For the slaves which are spawned dynamically, this approach does not work. I tried to forward the access to docker like

VOLUME /var/run/docker.sock
VOLUME /var/lib/docker

during building the image. Unfortunately so far I get a Permission denied (socket: /run/docker.sock) when trying to access to docker.sock in the slave which was created like: https://gist.github.com/geoHeil/1752b46d6d38bdbbc460556e38263bc3 The strange thing is: the user in the slave is root.

So why do I not have access to the docker.sock? Or how could I burn in the --privileged flag so that the permission denied problem would go away?


Solution

  • With docker 1.10 a new User namespace is introduced, thus sharing docker.sock isn't enough, as root inside the container isn't root on the host machine anymore. I recently played with Jenkins container as well, and I wanted to build containers using the host docker engine. The steps I did are:

    Find group id for docker group:

    $ id
    ..... 999(docker)
    

    Run jenkins container with two volumes - one contains the docker client executable, the other shares the docker unix socket. Note how I use --group-add to add the container user to the docker group, to allow access:

    docker run --name jenkins -tid -p 8080:8080 --group-add=999 -v /path-to-my-docker-client:/home/jenkins/docker -v /var/run/docker.sock:/var/run/docker.sock jenkins
    

    Tested and found it indeeds work:

    docker exec -ti jenkins bash
    ./docker ps
    

    See more about additional groups here

    Another approach would be to use --privileged flag instead of --group-add, yet its better to use avoid it if possible