一、实验环境


selinux iptables off

主机名

IP

系统版本

gitlab

10.10.10.200

rhel7.5

jenkins

10.10.10.10

rhel7.5

tomcat

10.10.10.11

rhel7.5

二、安装jenkins


1、解压安装包

下载地址:https://download.docker.com/linux/static/stable/x86_64/

[root@jenkins ~]# tar xf docker-18.06.3-ce.tgz
[root@jenkins ~]# cd docker/
[root@jenkins docker]# cp * /usr/bin/

2、配置docker.service

[root@jenkins ~]# vim /etc/systemd/system/docker.service
[Unit]
Description=Docker Application Container Engine
Documentation=https://docs.docker.com
After=network-online.target firewalld.service
Wants=network-online.target
 
[Service]
Type=notify
 
# the default is not to use systemd for cgroups because the delegate issues still
# exists and systemd currently does not support the cgroup feature set required
# for containers run by docker
ExecStart=/usr/bin/dockerd
ExecReload=/bin/kill -s HUP $MAINPID
 
# Having non-zero Limit*s causes performance problems due to accounting overhead
# in the kernel. We recommend using cgroups to do container-local accounting.
LimitNOFILE=infinity
LimitNPROC=infinity
LimitCORE=infinity

# Uncomment TasksMax if your systemd version supports it.
# Only systemd 226 and above support this version.
#TasksMax=infinity
TimeoutStartSec=0
 
# set delegate yes so that systemd does not reset the cgroups of docker containers
Delegate=yes
 
# kill only the docker process, not all processes in the cgroup
KillMode=process
 
# restart the docker process if it exits prematurely
Restart=on-failure
StartLimitBurst=3
StartLimitInterval=60s
 
[Install]
WantedBy=multi-user.target

3、启动docker

[root@jenkins ~]# chmod +x /etc/systemd/system/docker.service
[root@jenkins ~]# systemctl daemon-reload
[root@jenkins ~]# systemctl enable docker && systemctl restart docker

4、修改镜像源

[root@jenkins ~]# cat /etc/docker/daemon.json
{
 "registry-mirrors": ["https://docker.mirrors.ustc.edu.cn"]
}

[root@jenkins ~]# systemctl restart docker

三、gitlab安装


1、安装

[root@gitlab ~]# curl -sS https://packages.gitlab.com/install/repositories/gitlab/gitlab-ce/script.rpm.sh | sudo bash
[root@gitlab ~]# yum install -y gitlab-ce

2、初始化GitLab配置

[root@gitlab ~]# gitlab-ctl reconfigure

其他命令:

# 启动 gitlab 服务
gitlab-ctl start

# 停止 gitlab 服务
gitlab-ctl stop

3、浏览器登陆

http://10.10.10.200

[root@gitlab ~]# cat /etc/gitlab/initial_root_password

jenkins镜像源设置 jenkins镜像制作_docker

jenkins镜像源设置 jenkins镜像制作_jenkins_02

4、修改root密码

jenkins镜像源设置 jenkins镜像制作_tomcat_03

jenkins镜像源设置 jenkins镜像制作_tomcat_04


jenkins镜像源设置 jenkins镜像制作_tomcat_05

5、上传项目

jenkins镜像源设置 jenkins镜像制作_运维_06

四、tomcat安装


1、解压

[root@server1 ~]# tar xf jdk-8u45-linux-x64.tar.gz
[root@server1 ~]# mv jdk1.8.0_45/ /usr/local/jdk

2、声明变量

[root@server1 ~]# vim /etc/profile
export JAVA_HOME=/usr/local/jdk
export CLASSPATH=.:$JAVA_HOME/lib:$JAVA_HOME/jre/lib
export PATH=$PATH:$JAVA_HOME/bin

[root@server1 ~]# . /etc/profile

3、安装Tomcat

官网下载地址:https://tomcat.apache.org/download-80.cgi

[root@server1 ~]# tar xf apache-tomcat-8.5.59.tar.gz
[root@server1 ~]# mv apache-tomcat-8.5.59 /usr/local/tomcat

4、启动Tomcat

[root@server1 ~]# /usr/local/tomcat/bin/startup.sh 
[root@server1 ~]# /usr/local/tomcat/bin/shutdown.sh       ###关闭

5、查看Tomcat

jenkins镜像源设置 jenkins镜像制作_tomcat_07

五、jenkins安装


1、拉取镜像

[root@jenkins ~]# docker pull jenkins/jenkins:lts
[root@jenkins ~]# docker images
REPOSITORY             TAG          IMAGE ID       CREATED        SIZE
jenkins/jenkins        lts          825c3e86c65d   4 weeks ago    471MB

2、解压文件

JDK官方下载地址:https://www.oracle.com/java/technologies/downloads/
JDK三方下载地址:http://www.codebaoku.com/jdk/jdk-oracle-jdk1-8.html
maven下载地址:https://mirrors.aliyun.com/apache/maven/maven-3/

[root@jenkins ~]# tar xf jdk-8u45-linux-x64.tar.gz
[root@jenkins ~]# mv jdk1.8.0_45/ /usr/local/jdk
[root@jenkins ~]# tar xf apache-maven-3.5.0-bin.tar.gz
[root@jenkins ~]# mv apache-maven-3.5.0 /usr/local/maven

3、配置maven阿里云仓库

[root@jenkins ~]# vim /usr/local/maven/conf/settings.xml
<mirrors>
  <mirror>
    <id>central</id>
    <mirrorOf>central</mirrorOf>
    <name>aliyun maven</name>
    <url>https://maven.aliyun.com/repository/public</url>
  </mirror>
</mirrors>

4、运行jenkins

docker run -d --name jenkins -p 8080:8080 -p 50000:50000 -u root \
-v /opt/jenkins_home:/var/jenkins_home \
-v /usr/local/maven:/usr/local/maven \
-v /usr/local/jdk:/usr/local/jdk \
-v /etc/localtime:/etc/localtime \
-v /usr/bin/docker:/usr/bin/docker \
-v /var/run/docker.sock:/var/run/docker.sock \
-e TZ="Asia/Shanghai" \
--restart=always \
jenkins/jenkins:lts

5、查看密码

[root@jenkins ~]# cd /opt/jenkins_home/
[root@jenkins jenkins_home]# sed -i ‘s#https://updates.jenkins.io/update-center.json#http://mirror.esuni.jp/jenkins/updates/update-center.json#g’ hudson.model.UpdateCenter.xml
[root@jenkins jenkins_home]# systemctl restart docker

[root@jenkins ~]# cat /opt/jenkins_home/secrets/initialAdminPassword
375dd3d01ef9411b833a8860d028683d

6、通过密码登录

jenkins镜像源设置 jenkins镜像制作_运维_08

7、安装插件

jenkins镜像源设置 jenkins镜像制作_docker_09


jenkins镜像源设置 jenkins镜像制作_tomcat_10

8、创建管理员用户

jenkins镜像源设置 jenkins镜像制作_jenkins_11

9、安装重启

jenkins镜像源设置 jenkins镜像制作_jenkins镜像源设置_12


jenkins镜像源设置 jenkins镜像制作_docker_13

10、修改为国内源

[root@jenkins ~]# cd /opt/jenkins_home/updates/
[root@jenkins updates]# sed -i 's/https:\/\/updates.jenkins.io\/download/https:\/\/mirrors.tuna.tsinghua.edu.cn\/jenkins/g' default.json
[root@jenkins updates]# sed -i 's/http:\/\/www.google.com/https:\/\/www.baidu.com/g' default.json

六、通过FreeStyle发布


提前下载git parameterPublish Over SSH插件,git parameter版本低于0.95正常,否则报错:Retrieving Git references,无法获取到正常版本

1、配置Tomcat SSH Server

Manage Jenkins -> Configure System -> Public over SSH

jenkins镜像源设置 jenkins镜像制作_jenkins_14

2、创建FreeStyle项目

jenkins镜像源设置 jenkins镜像制作_jenkins镜像源设置_15

3、配置git参数

jenkins镜像源设置 jenkins镜像制作_tomcat_16

4、git拉取地址设置

jenkins镜像源设置 jenkins镜像制作_jenkins镜像源设置_17

5、maven编译

如果指定对应模块编译:mvn clean package -am -Dmaven.test.skip=true -pl [module]

jenkins镜像源设置 jenkins镜像制作_docker_18

JAVA_HOME=/usr/local/jdk
PATH=$PATH:$JAVA_HOME/bin
/usr/local/maven/bin/mvn clean package -Dmaven.test.skip=true

jenkins镜像源设置 jenkins镜像制作_docker_19

6、Tomcat服务器执行程序

tomcat=/usr/local/tomcat
cd $tomcat/webapps
rm -rf $tomcat/webapps/ROOT
mv *.war /data/backup/$(date +"%F_%T")_ROOT.war
# 部署新程序并重启Tomcat
mv /tmp/$JOB_NAME/*.war  $tomcat/webapps/ROOT.war
pid=$(ps -ef |grep $tomcat |egrep -v 'grep' |awk '{print $2}')
[ -n "$pid" ] && kill -9 $pid
export  JAVA_HOME=/usr/local/jdk
/bin/bash /usr/local/tomcat/bin/startup.sh

jenkins镜像源设置 jenkins镜像制作_运维_20

7、构建并查看结果

jenkins镜像源设置 jenkins镜像制作_docker_21


jenkins镜像源设置 jenkins镜像制作_docker_22

七、通过Maven发布


安装插件Maven IntegrationVersion 3.22

1、配置JDK和maven

系统管理->全局工具配置

jenkins镜像源设置 jenkins镜像制作_jenkins_23

jenkins镜像源设置 jenkins镜像制作_jenkins_24

2、创建maven项目

jenkins镜像源设置 jenkins镜像制作_tomcat_25

3、配置Git参数

jenkins镜像源设置 jenkins镜像制作_docker_26

4、git拉取地址设置

jenkins镜像源设置 jenkins镜像制作_运维_27

5、maven编译

clean package -DskipTests=true

jenkins镜像源设置 jenkins镜像制作_tomcat_28

6、Tomcat服务器执行脚本

tomcat=/usr/local/tomcat
cd $tomcat/webapps
rm -rf $tomcat/webapps/ROOT
mv *.war /data/backup/$(date +"%F_%T")_ROOT.war
# 部署新程序并重启Tomcat
mv /tmp/$JOB_NAME/*.war  $tomcat/webapps/ROOT.war
pid=$(ps -ef |grep $tomcat |egrep -v 'grep' |awk '{print $2}')
[ -n "$pid" ] && kill -9 $pid
export  JAVA_HOME=/usr/local/jdk
/bin/bash /usr/local/tomcat/bin/startup.sh

jenkins镜像源设置 jenkins镜像制作_docker_29

7、构建并查看结果

jenkins镜像源设置 jenkins镜像制作_运维_30


jenkins镜像源设置 jenkins镜像制作_jenkins镜像源设置_31

八、通过Pipline发布


1、创建流水线项目

jenkins镜像源设置 jenkins镜像制作_tomcat_32

2、配置git参数

jenkins镜像源设置 jenkins镜像制作_运维_33

3、流水线语法

jenkins镜像源设置 jenkins镜像制作_jenkins镜像源设置_34

4、git拉取流水线脚本

jenkins镜像源设置 jenkins镜像制作_tomcat_35

5、maven编译流水线脚本

jenkins镜像源设置 jenkins镜像制作_docker_36

6、发送并启动流水线脚本

jenkins镜像源设置 jenkins镜像制作_docker_37

7、配置流水线脚本

:如果Publish over ssh想使用变量,要使用双引号,例如sourceFiles(默认是单引号)
如果想实现war包可下载:archiveArtifacts

pipeline {
    agent any 
    stages {
        stage('拉取代码') { 
            steps {
                checkout scmGit(branches: [[name: '$Branch']], extensions: [], userRemoteConfigs: [[credentialsId: 'e94bf465-be00-490b-9f24-856106362015', url: 'http://10.10.10.200/wielun/java-test.git']])
            }
        }
        stage('maven编译') { 
            steps {
                sh '''JAVA_HOME=/usr/local/jdk
                PATH=$PATH:$JAVA_HOME/bin
                /usr/local/maven/bin/mvn clean package -Dmaven.test.skip=true'''
            }
        }
        stage('发送到tomcat服务器并启动') { 
            steps {
                sshPublisher(publishers: [sshPublisherDesc(configName: 'tomcat-test', transfers: [sshTransfer(cleanRemote: false, excludes: '', execCommand: '''tomcat=/usr/local/tomcat
                cd $tomcat/webapps
                rm -rf $tomcat/webapps/ROOT
                mv *.war /data/backup/$(date +"%F_%T")_ROOT.war
                # 部署新程序并重启Tomcat
                mv /tmp/$JOB_NAME/*.war  $tomcat/webapps/ROOT.war
                pid=$(ps -ef |grep $tomcat |egrep -v \'grep\' |awk \'{print $2}\')
                [ -n "$pid" ] && kill -9 $pid
                export  JAVA_HOME=/usr/local/jdk
                /bin/bash /usr/local/tomcat/bin/startup.sh''', execTimeout: 120000, flatten: false, makeEmptyDirs: false, noDefaultExcludes: false, patternSeparator: '[, ]+', remoteDirectory: '$JOB_NAME', remoteDirectorySDF: false, removePrefix: 'target', sourceFiles: 'target/*.war')], usePromotionTimestamp: false, useWorkspaceInPromotion: false, verbose: false)])
            }
        }
    }
}

jenkins镜像源设置 jenkins镜像制作_jenkins_38

8、构建并查看结果

注:第一次看不到分支,构建一次就好了

jenkins镜像源设置 jenkins镜像制作_jenkins_39

jenkins镜像源设置 jenkins镜像制作_jenkins_40

jenkins镜像源设置 jenkins镜像制作_jenkins镜像源设置_41

9、前端vue pipeline

pipeline {
    agent any

    tools {
        nodejs "node"
    }
    
    environment { 
        TAR_NAME = "wielun"
        BRANCH_NAME = "*/test"
        CREDENTIALS_ID = "e87fcb1b-xxxx-4ed7-xxxx-16d1ca8bf5fb"
        GIT_URL = "https://gitee.com/xxx.git"
        CONFIG_NAME = "wielun-test"
        BACKUP_PATH = "/data/backup"
        SOURCE_PATH = "/tmp/${JOB_NAME}"
        DEST_PATH = "/mnt/wielun/project/nginx/www"
        RETENTION_NUM = 2
    }
    
    stages {
        stage('git拉取代码') {
            steps {
                checkout scmGit(branches: [[name: "${BRANCH_NAME}"]], extensions: [], userRemoteConfigs: [[credentialsId: "${CREDENTIALS_ID}", url: "${GIT_URL}"]])
            }
        }
        stage('编译代码') {
            steps {
                sh ''' 
                    pnpm config set registry https://registry.npm.taobao.org
                    pnpm install
                    pnpm run build
                    
                    mv dist ${TAR_NAME}
                    tar zcvf ${TAR_NAME}.tar.gz ${TAR_NAME}
                    rm -rf ${TAR_NAME}
                '''
            }
        }
        stage('发布tar包') {
            steps {
                archiveArtifacts "${TAR_NAME}.tar.gz"
            }
        }
        stage('发送到服务器') {
            steps {
                script() {
                    deploy()
                }
            }
        }
    }
}

def deploy() {
    sshPublisher(
        publishers: [
            sshPublisherDesc(
                configName: "${CONFIG_NAME}",
                transfers: [
                    sshTransfer(
                        cleanRemote: false, 
                        excludes: '', 
                        execCommand: """
                            mkdir -p ${BACKUP_PATH}/${JOB_NAME}
                            mv ${DEST_PATH}/${TAR_NAME} ${BACKUP_PATH}/${JOB_NAME}/${TAR_NAME}_\$(date +"%F_%T")
                            tar xf ${SOURCE_PATH}/${TAR_NAME}.tar.gz -C ${DEST_PATH}
                            rm -f ${SOURCE_PATH}/${TAR_NAME}.tar.gz
                            ls -t ${BACKUP_PATH}/${JOB_NAME} | awk "NR>${RETENTION_NUM}" | xargs rm -rf
                        """, 
                        execTimeout: 120000, 
                        flatten: false, 
                        makeEmptyDirs: false, 
                        noDefaultExcludes: false, 
                        patternSeparator: '[, ]+', 
                        remoteDirectory: "${JOB_NAME}", 
                        remoteDirectorySDF: false, 
                        removePrefix: "", 
                        sourceFiles: "${TAR_NAME}.tar.gz")], 
                        usePromotionTimestamp: false, 
                        useWorkspaceInPromotion: false, 
                        verbose: true)
        ])
}

九、设置环境变量


1、读取文件变量

pipeline {
    stages {
        stage('读取文件变量') {
            steps {
                script {
                    def fileContent = readFile('a').trim()
                    env.MY_GLOBAL_VARIABLE = fileContent
                }
                
            }
        }

        stage("获取变量") {
            steps {
                sh "printenv"
                sh """
                    echo ${MY_GLOBAL_VARIABLE}
                """
            }
        }
    }
}