Run Docker as jenkins-agent, in a docker-container, as non-root user

…衆ロ難τιáo~ 提交于 2019-12-20 06:27:06

问题


Simular Questions

  • Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock
  • How to solve Docker permission error when trigger by Jenkins
  • https://github.com/jenkinsci/docker/issues/263

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.


回答1:


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.



来源:https://stackoverflow.com/questions/54452152/run-docker-as-jenkins-agent-in-a-docker-container-as-non-root-user

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!