简体   繁体   中英

How to build on a host when running Jenkins inside a Docker container

I am running a Jenkins instance within a Docker container, and it is connected to a Bitbucket repository. When something changes in the online repository, Jenkins downloads the new source. Based on the new source, I want to create a new Docker image, but that needs to happen on the host since it is where I have Docker installed.

I haven't figured out how can I run something on the host, but at the same time I understand that Docker is used for isolating processes, so this is by design. Is there a way to achieve this?

I would create a separate Jenkins slave that maps to either the host running Jenkins, or a separate host that has Docker installed. Then run your job to create Docker images on the slave rather than the master.

The documentation for the official Jenkins Docker image has details on how to connect up a slave.

It is possible to use Docker from a host inside your Jenkins container. You need to install Docker on the container and then map the host's Docker socket descriptor.

A sample Dockerfile that will achieve this could looks like this:

FROM jenkins/jenkins:2.102

USER root

RUN apt-get update && \
    apt-get install -y \
    apt-transport-https \
    software-properties-common

# Docker
RUN curl -fsSL https://download.docker.com/linux/ubuntu/gpg | apt-key add - && \
    add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu xenial stable" && \
    apt-get update && apt-get install -y docker-ce && \
    usermod -aG docker,staff jenkins

# Set SUID to run docker as root
RUN chmod g+s /usr/bin/docker

USER jenkins

To run a container based on this image with Docker working, you need to map the docker.sock file descriptor:

docker run -p 8080:8080 -v /var/run/docker.sock:/var/run/docker.sock my-image

If you don't want to building a new image you can use my prebuilt image: https://hub.docker.com/r/mdobak/docker-jenkins/

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