Creating a Jenkins Server in a Docker Container
Are you looking for article that shows how to create a Jenkins server in Docker container ? This article might help you on that.
Before reading this article we hope that you have some understating on how docker containerization works. If you are new to docker its better you follow these official Docker documentation before going through this article.
So lets get started .
In this article we will be using the below folder structure. Project folder would be JENKINS
Let me explain what are the files ->
JENKINS/configs/users/admin/config.xml this file contains the jenkins user details. Beacuse in jenkins we need to create a jenkins user who has the access to run scripts , install plugins and run tests.
<?xml version="1.0" encoding="UTF-8"?>
<user>
<fullName>admin</fullName>
<properties>
<jenkins.security.ApiTokenProperty>
<apiToken>nDByjglevCpwNwQkyx21eOPp86vL4P/m1DFJSae+gJvMMRClpO5raH+wCpKQsBvv</apiToken>
</jenkins.security.ApiTokenProperty>
<hudson.model.MyViewsProperty>
<views>
<hudson.model.AllView>
<owner class="hudson.model.MyViewsProperty" reference="../../.." />
<name>All</name>
<filterExecutors>false</filterExecutors>
<filterQueue>false</filterQueue>
<properties class="hudson.model.View$PropertyList" />
</hudson.model.AllView>
</views>
</hudson.model.MyViewsProperty>
<hudson.model.PaneStatusProperties>
<collapsed />
</hudson.model.PaneStatusProperties>
<hudson.search.UserSearchProperty>
<insensitiveSearch>false</insensitiveSearch>
</hudson.search.UserSearchProperty>
<hudson.security.HudsonPrivateSecurityRealm_-Details>
<passwordHash>#jbcrypt:$2a$10$KZr7NUlLVTbMykYeuYLdPOgT/jFSfiLZHI3tqU.BkkzW3chSYi9Ha</passwordHash>
</hudson.security.HudsonPrivateSecurityRealm_-Details>
<jenkins.security.LastGrantedAuthoritiesProperty>
<roles>
<string>authenticated</string>
</roles>
<timestamp>1486734797021</timestamp>
</jenkins.security.LastGrantedAuthoritiesProperty>
</properties>
</user>
JENKINS/configs/jenkins_home_config.xml
This config file that supports the Jenkins users permission and security configurations.
<?xml version="1.0" encoding="UTF-8"?>
<hudson>
<disabledAdministrativeMonitors />
<version>1.0</version>
<numExecutors>2</numExecutors>
<mode>NORMAL</mode>
<useSecurity>true</useSecurity>
<authorizationStrategy class="hudson.security.FullControlOnceLoggedInAuthorizationStrategy">
<denyAnonymousReadAccess>true</denyAnonymousReadAccess> </authorizationStrategy>
<securityRealm class="hudson.security.HudsonPrivateSecurityRealm"> <disableSignup>false</disableSignup> <enableCaptcha>false</enableCaptcha>
</securityRealm>
<disableRememberMe>false</disableRememberMe> <projectNamingStrategy class="jenkins.model.ProjectNamingStrategy$DefaultProjectNamingStrategy" />
<workspaceDir>${ITEM_ROOTDIR}/workspace</workspaceDir> <buildsDir>${ITEM_ROOTDIR}/builds</buildsDir>
<markupFormatter class="hudson.markup.EscapedMarkupFormatter" /> <jdks />
<viewsTabBar class="hudson.views.DefaultViewsTabBar" /> <myViewsTabBar class="hudson.views.DefaultMyViewsTabBar" /> <clouds />
<scmCheckoutRetryCount>0</scmCheckoutRetryCount>
<views>
<hudson.model.AllView>
<owner class="hudson" reference="../../.." /> <name>All</name>
<filterExecutors>false</filterExecutors> <filterQueue>false</filterQueue>
<properties class="hudson.model.View$PropertyList" /> </hudson.model.AllView>
</views>
<primaryView>All</primaryView> <slaveAgentPort>50000</slaveAgentPort>
<label />
<nodeProperties />
<globalNodeProperties />
</hudson>
JENKINS/configs/my_super_job_config.xml
These are the jenkins jobs. If you have a existing jenkins server and you want to reuse the same jobs you can follow this link and get a .xml file like below.
<?xml version='1.1' encoding='UTF-8'?><project><actions/><description></description><keepDependencies>false</keepDependencies><properties/><scm class="hudson.plugins.git.GitSCM" plugin="git@4.2.2"><configVersion>2</configVersion><userRemoteConfigs><hudson.plugins.git.UserRemoteConfig><url>https://sheshanGamage@novigi-business-services-process-improvements.git</url><credentialsId>Hi From Sri Lanka</credentialsId></hudson.plugins.git.UserRemoteConfig></userRemoteConfigs><branches><hudson.plugins.git.BranchSpec><name>*/master</name></hudson.plugins.git.BranchSpec></branches><doGenerateSubmoduleConfigurations>false</doGenerateSubmoduleConfigurations><submoduleCfg class="list"/><extensions/></scm><canRoam>true</canRoam><disabled>false</disabled><blockBuildWhenDownstreamBuilding>false</blockBuildWhenDownstreamBuilding><blockBuildWhenUpstreamBuilding>false</blockBuildWhenUpstreamBuilding><triggers><com.cloudbees.jenkins.plugins.BitBucketTrigger plugin="bitbucket@1.1.11"><spec></spec></com.cloudbees.jenkins.plugins.BitBucketTrigger></triggers><concurrentBuild>false</concurrentBuild><builders><hudson.tasks.Shell><command>cd /var/jenkins_home/jobs/my_super_job/workspace/EI-MysqlTestecho "inside the Test Folder"./deploy.sh -h localhost -p 9443exit 0</command></hudson.tasks.Shell></builders><publishers/><buildWrappers/></project>
JENKINS/configs/my_ultra_job_config.xml
Another jenkins job xml file
<?xml version='1.0' encoding='UTF-8'?><project><description></description><keepDependencies>false</keepDependencies><properties/><scm class="hudson.scm.NullSCM"/><canRoam>true</canRoam><disabled>false</disabled><blockBuildWhenDownstreamBuilding>false</blockBuildWhenDownstreamBuilding><blockBuildWhenUpstreamBuilding>false</blockBuildWhenUpstreamBuilding><triggers/><concurrentBuild>false</concurrentBuild><builders/><publishers/><buildWrappers/></project>
JENKINS/docker-compose.yml
Compose is a tool for defining and running multi-container Docker applications. With Compose, you use a YAML file to configure your application’s services. Then, with a single command, you create and start all the services from your configuration.
jenkins2:container_name: j2image: j2:v1environment:JAVA_OPTS: "-Djava.awt.headless=true"JAVA_OPTS: "-Djenkins.install.runSetupWizard=false" # Start jenkins unlockedports:- "50000:50000"- "8080:8080"volumes:- /var/jenkins_home
JENKINS/Dockerfile
A Dockerfile is a text document that contains all the commands a user could call on the command line to assemble an image. Using docker build users can create an automated build that executes several command-line instructions in succession.The file we used in this downloads a image from the docker repo and install Maven , Node and install jenkins plugins to run our jenkin jobs.
FROM jenkins/jenkins:alpineENV JENKINS_USER adminENV JENKINS_PASS admin# Skip initial setupENV JAVA_OPTS -Djenkins.install.runSetupWizard=falseCOPY plugins.txt /usr/share/jenkins/plugins.txtRUN /usr/local/bin/install-plugins.sh < /usr/share/jenkins/plugins.txtUSER rootRUN apk add dockerRUN apk add py-pipRUN apk add python-dev libffi-dev openssl-dev gcc libc-dev makeRUN pip install docker-composeCOPY /configs/users "$JENKINS_HOME"/users/# Install MavenRUN apk add --no-cache curl tar bashARG MAVEN_VERSION=3.6.3ARG USER_HOME_DIR="/root"RUN mkdir -p /usr/share/maven && \curl -fsSL http://apache.osuosl.org/maven/maven-3/$MAVEN_VERSION/binaries/apache-maven-$MAVEN_VERSION-bin.tar.gz | tar -xzC /usr/share/maven --strip-components=1 && \ln -s /usr/share/maven/bin/mvn /usr/bin/mvnENV MAVEN_HOME /usr/share/mavenENV MAVEN_CONFIG "$USER_HOME_DIR/.m2"# Add the main config file to the jenkins pathCOPY /configs/jenkins_home_config.xml "$JENKINS_HOME"/config.xml# Name the jobsARG job_name_1="my_super_job"ARG job_name_2="my_ultra_job"# Create the job workspacesRUN mkdir -p "$JENKINS_HOME"/workspace/${job_name_1}RUN mkdir -p "$JENKINS_HOME"/workspace/${job_name_2}# Create the jobs folder recursivelyRUN mkdir -p "$JENKINS_HOME"/jobs/${job_name_1}RUN mkdir -p "$JENKINS_HOME"/jobs/${job_name_2}# Add the custom configs to the containerCOPY /configs/${job_name_1}_config.xml "$JENKINS_HOME"/jobs/${job_name_1}/config.xmlCOPY /configs/${job_name_2}_config.xml "$JENKINS_HOME"/jobs/${job_name_2}/config.xml# Create build file structureRUN mkdir -p "$JENKINS_HOME"/jobs/${job_name_1}/latest/RUN mkdir -p "$JENKINS_HOME"/jobs/${job_name_1}/builds/1/# Create build file structureRUN mkdir -p "$JENKINS_HOME"/jobs/${job_name_2}/latest/RUN mkdir -p "$JENKINS_HOME"/jobs/${job_name_2}/builds/1/RUN apk add --update nodejs nodejs-npmRUN npm install -g newmanRUN npm install -g newman-reporter-html
JENKINS/plugins.txt
This file contains all the jenkins plugins that needs to run your jenkin jobs. This list contains some of the popular jenkins plugins.
ace-editorantantisamy-markup-formatterbranch-apicloudbees-foldercredentialscvsdockerdurable-taskexternal-monitor-jobgit-clientgit-servergitgithub-apigithub-branch-sourcegithubjavadocjquery-detachedjunitldapmailermatrix-authmatrix-projectmaven-pluginmetricspam-authplain-credentialsscm-apiscript-securityssh-credentialsssh-slavessubversiontranslationvariantwindows-slavesworkflow-aggregatorworkflow-apiworkflow-basic-stepsworkflow-cps-global-libworkflow-cpsworkflow-durable-task-stepworkflow-jobworkflow-multibranchworkflow-scm-stepworkflow-step-apiworkflow-supportfavoritetoken-macropipeline-stage-stepblueoceanblueocean-autofavoritegitlab-plugin
Now we have all the files in our project. So lets run and build the jenkins docker container.Please run all these comands from inside the JENKINS project folder.
Command to create the jenkins image
sudo docker build -t j2:v1 . --no-cache
Command to run the created jenkins image.
sudo docker run --network="host" j2:v1
If you have ran the project several times you would see something like this.
:) Thank You
hope you learnt something from this :)