Run Docker as jenkins-agent, in a docker-container

2020-05-09 14:43发布

Simular Questions

Dockerfile

FROM  jenkins/jenkins:lts
USER root
RUN apt-get -qq update  && apt-get -qq -y install --no-install-recommends curl
RUN curl -sSL https://get.docker.com/ | sh
RUN usermod -aG docker jenkins
USER jekins

Terminal command

docker run -p 8080:8080 -p 50000:50000 \
  -v jenkins_home:/var/jenkins_home \
  -v /var/run/docker.sock:/var/run/docker.sock \
  -ti bluebrown/docker-in-jenkins-in-docker /bin/bash

Inside the container

docker image ls

Output

Got permission denied while trying to connect to the Docker daemon
socket at unix:///var/run/docker.sock: Get
http://%2Fvar%2Frun%2Fdocker.sock/v1.39/images/json: dial unix
/var/run/docker.sock: connect: permission denied

When I comment the last line of the dockerfile out, to run the instance as root user,

# USER jenkins

I can access the docker socket without issues, for obvious reasons. However, I think this is not a proper solution. That is why I want to ask if anyone managed to access the docker socket as non root user.

2条回答
Deceive 欺骗
2楼-- · 2020-05-09 15:28

You've added the docker group to the Jenkins user inside the container. However, that will not necessarily work because the mapping of users and groups to uids and gids can be different between the host and container. That's normally not an issue, but with host volumes and other bind mounts into the container, the files are mapped with the same uid/gid along with the permissions. Therefore, inside the container, the docker group will not have access to the docker socket unless the gid happens to be identical between the two environments.

There are several solutions, including manually passing the host gid as the gid to use inside the container. Or you can get the gid of the host and build the image with that value hard coded in.

My preferred solution is to start an entrypoint as root, fix the docker group inside the container to match the gid of the mounted docker socket, and then switch to the Jenkins user to launch the app. This works especially well in development environments where control of uid/gids may be difficult. All the steps/scripts for this are in my repo: https://github.com/sudo-bmitch/jenkins-docker

For production in a controlled environment, I try to get standardized uid/gid values, both on the host and in containers, for anything that mounts host volumes. Then I can run the container without the root entrypoint steps.

查看更多
不美不萌又怎样
3楼-- · 2020-05-09 15:34

In your dockerfile you are enabling docker access for the user jenkins but droping down to the user jekins not jenkins?

Is this just a typo on this page?

I use this approach as you've described and it works correctly.

查看更多
登录 后发表回答