1.编写Dockfile文件
~jenkins的docker 镜像 带maven+git+jdk1.8
#最新版的 jenkins 自带jdk1.8
FROM jenkins
USER root
# install git
RUN apt-get install git -y
RUN apt-get update && apt-get install -y sudo && rm -rf /var/lib/apt/lists/*
RUN echo "jenkins ALL=NOPASSWD: ALL" >> /etc/sudoers
ARG dockerGid=999
RUN echo "docker:x:${dockerGid}:jenkins" >> /etc/group
#下载解压mvn
ENV MAVEN_VERSION=3.5.2
RUN mkdir /usr/local/maven &&\
wget http://archive.apache.org/dist/maven/maven-3/$MAVEN_VERSION/binaries/apache-maven-$MAVEN_VERSION-bin.tar.gz && \
tar -zxvf apache-maven-$MAVEN_VERSION-bin.tar.gz && \
rm apache-maven-$MAVEN_VERSION-bin.tar.gz && \
mv apache-maven-$MAVEN_VERSION/* /usr/local/maven && \
rm -r apache-maven-$MAVEN_VERSION
ENV MAVEN_HOME /usr/local/maven
ENV PATH $PATH:$MAVEN_HOME/bin
#测试
RUN mvn -version
RUN java -version
#调整时区
ENV TZ=Asia/Shanghai
ENV LANG="zh_CN.UTF-8"
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone \
&& echo "export LC_ALL=zh_CN.UTF-8" >> /etc/profile
#测试
RUN date
USER jenkins
2.在宿主机中构建docker镜像
sudo docker build -t ssm/jenkins:1.0 .
3.在宿主机中创建jenkins的挂载目录,并授权
mkdir jenkins_home
#不授权 的话会导致宿主机 /opt/jenkins_home 是root用户,而容器中映射的目录属于jenkins用户,导致异常 Permission denied
sudo chown -R 1000 /opt/jenkins_home
4.运行docker生成容器
~在容器内也能运行docker指令
#run
sudo docker run -p 8090:8080 -p 50000:50000 --name jenkins \
--restart=always \
-v $(which docker):/usr/bin/docker \
-v /var/run/docker.sock:/var/run/docker.sock \
-v /usr/lib/jvm/java-8-oracle:/usr/local/jdk \
-v /opt:/opt \
-v /usr/share/maven:/usr/local/maven \
-v /opt/jenkins_home:/var/jenkins_home \
-v ~/.ssh:/var/jenkins_home/.ssh \
-v /usr/lib/x86_64-linux-gnu/libltdl.so.7:/usr/lib/x86_64-linux-gnu/libltdl.so.7 \
-v /etc/timezone:/etc/timezone \
-v /etc/localtime:/etc/localtime \
-d ssm/jenkins:1.0
5.jenkins shell脚本
#!/bin/bash
echo '>>> START exec shell'
jarName=admin.jar
dockerName=admin
basePath=/opt/admin
module=admin
datename=$basePath/back/$(date +%Y%m%d-%H%M)
echo '>>> mvn clean package -all'
mvn clean package
echo '>>> stop the docker container'
if sudo docker ps -a|grep -i $dockerName;then
sudo docker stop $dockerName
fi
echo '>>>delete old jar'
sudo rm -r $basePath/$jarName
echo '>>>end delete'
#echo '>>>start backup jar'
#sudo mkdir $datename
#sudo mv $basePath/$jarName $datename/
#echo '>>>end backup'
echo '>>> cp jar to prod'
sudo cp $module/target/$jarName $basePath/
echo '>>> start the docker container'
sudo docker start $dockerName
echo '>>> END exec shell'
网友评论