36
Run Docker commands inside Jenkins Docker container
If you want to initiate docker containers from within your jenkin containers,this is what you have to do:
- In the Jenkins Dockerfile, add commands to get docker, docker-compose installed.
- bind mount the docker socket.
And thats it! This is how the Dockerfile looks like:
FROM jenkins/jenkins
# Docker install
USER root
RUN apt-get update && apt-get install -y \
apt-transport-https \
ca-certificates \
curl \
gnupg2 \
software-properties-common \
RUN curl -fsSL https://download.docker.com/linux/debian/gpg | apt-key add -
RUN apt-key fingerprint 0EBFCD88
RUN add-apt-repository \
"deb [arch=amd64] https://download.docker.com/linux/debian \
$(lsb_release -cs) \
stable"
RUN curl -L https://github.com/docker/compose/releases/download/1.27.4/docker-compose-`uname -s`-`uname -m` -o /usr/local/bin/docker-compose \
&& chmod +x /usr/local/bin/docker-compose
RUN apt-get update && apt-get install -y docker-ce-cli
USER jenkins
Now to build the image:
docker build -t jenkins-docker .
To run the docker-image, including the volume mounts:
docker run -d --group-add $(stat -c '%g' /var/run/docker.sock) \
-v /var/run/docker.sock:/var/run/docker.sock -p 8080:8080 -p 50000:50000 \
-v `pwd`/jenkins:/var/jenkins_home --log-opt max-size=50k --log-opt max-file=5 --name jenkins -P jenkins-docker
Here you can see docker.sock file has been mounted.Also, jenkins_home folder has been mounted so that you can persist the information regarding your pipeline/configuration/users etc.
Dont forget to take backup of jenkins_home directory!
I have uploaded a makefile and a similar Dockerfile on github.
And thats it!
36