简体   繁体   中英

Access docker.sock from inside a container

I'm running a jenkins docker container from which I need to build and run dockers. The container is started using -v /var/run/docker.sock:/var/run/docker.sock . The problem is that I'm getting access denied when jenkins (from inside the container) tries to use it.

This is what I've tried so far with no luck:

  • Create a jenkins user in the host and add it to the docker group.
  • Start the docker daemon with the -G jenkins parameter so the socket is owned by the jenkins group instead of the docker one. Jenkins is being executed with a jenkins user that belongs to a jenkins group inside the container.

The only thing that worked was a "hack" that I don't like at all: I've modified the id of the jenkins group inside the container to match the group id of docker.sock .

Any suggestion on how to solve this in a more elegant way would be appreciated.

This sounds like a basic Unix permissions problem. To access a file (or socket), you need either (a) be root or (b) have a numeric UID or GID that permits you access based on the file mode.

If you are running something inside a container and you want it to have access to something on your host, you're going to have to either run things inside the container as root or you're going to have to work out uid/gid synchronization between the host and your container.

One way to deal with the latter problem is to pass in the target GID when you start the container and then have an ENTRYPOINT script set up the appopriate users/groups before starting your CMD. Something like:

if [ "$DOCKER_GID" ]; then
    groupadd -g $DOCKER_GID hostdocker
    usermod -a -G hostdocker jenkins
fi

exec "$@"

I had similar problems and in the end just gave the jenkins user passwordless sudo rights. This meant I had to prefix the all the docker commands with sudo, but it works and is portable between hosts.

You could create a special image with the jenkins user having the docker GID baked in. This might be called bad, since it is not portable:

FROM jenkins

USER root

RUN groupadd -g 999 hostdocker && usermod -G hostdocker -a jenkins
RUN wget https://get.docker.io/builds/Linux/x86_64/docker-1.7.1 -O /usr/local/bin/docker && chmod +x /usr/local/bin/docker

USER jenkins

ENTRYPOINT ["/bin/tini", "--", "/usr/local/bin/jenkins.sh"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM