一、在服务器上搭建Gitlab
本人阿里的服务器因配置有限,就直接使用Gitee作为代码仓库了
二、搭建Jenkins服务
集成Jenkins-1
1.安装JDK
Jenkins需要依赖JDK,所以先安装JDK1.8
yum install java-1.8.0-openjdk* -y
2.安装Jenkins
-
获取jenkins安装包 -
把安装包上传到服务器A,进行安装 rpm -ivh jenkins-2.190.3-1.1.noarch.rpm
-
修改Jenkins配置 vi /etc/sysco?g/jenkins
修改内容如下(修改访问Jenkins的端口): JENKINS_USER=“root” JENKINS_PORT=“3344”
-
启动Jenkins systemctl start jenkins
-
打开浏览器访问 http://xx.xxxx:3344 注意 :本服务器把防火墙关闭了,如果开启防火墙,需要在防火墙添加端口 -
获取并输入admin账户密码 cat /var/lib/jenkins/secrets/initialAdminPassword
-
跳过插件安装(官方的安装比较慢,甚至失败,进去后配置阿里的加速地址) -
添加一个管理员账户,并进入Jenkins后台
集成Jenkins-2
1.修改Jenkins插件下载地址
Jenkins国外官方插件地址下载速度非常慢,所以可以修改为国内插件地址: Jenkins->Manage Jenkins->Manage Plugins,点击Available
这样做是为了把Jenkins官方的插件列表下载到本地,接着修改地址文件,替换为国内插件地址
cd /var/lib/jenkins/updates
sed -i 's/http:\/\/updates.jenkinsci.org\/download/https:\/\/mirrors.tuna.tsinghua.edu.cn\/jenkins/g' default.json && sed -i 's/http:\/\/www.google.com/https:\/\/www.baidu.com/g' default.json
最后,Manage Plugins点击Advanced,把Update Site改为国内插件下载地址 https://mirrors.tuna.tsinghua.edu.cn/jenkins/updates/update-center.json
Sumbit后,在浏览器输入:http://192.168.66.101:8888/restart ,重启Jenkins。
2.下载中文汉化插件
Jenkins->Manage Jenkins->Manage Plugins,点击Available,搜索"Chinese"
3.安装Credentials Binding插件
要在Jenkins使用凭证管理功能,需要安装Credentials Binding插件
可以添加的凭证有5种:
- Username with password:用户名和密码
- SSH Username with private key: 使用SSH用户和密钥
- Secret ?le:需要保密的文本文件,使用时Jenkins会将文件复制到一个临时目录中,再将文件路径设置到一个变量中,等构建结束后,所复制的Secret ?le就会被删除。
- Secret text:需要保存的一个加密的文本串,如钉钉机器人或Github的api token
- Certi?cate:通过上传证书文件的方式
常用的凭证类型有:Username with password(用户密码)和SSH Username with private key(SSH密钥)
4.安装Git插件和Git工具
-
在Jenkins上的插件中安装Git插件 -
在服务器上也安装git yum install git -y 安装
git --version 安装后查看版本
-
创建凭证(用户密码类型) Jenkins->凭证->系统->全局凭证->添加凭证 选择"Username with password",输入Gitlab的用户名和密码,点击"确定"。之后在项目中就可以用该凭证了 -
创建凭证(SSH密钥类型) 在服务器A使用root用户生成公钥和私钥 ssh-keygen -t rsa
在`/root/.ssh/`目录保存了公钥和私钥
把生成的公钥放在Gitlab中
在Jenkins添加一个新的凭证,类型为"SSH Username with private key ",把刚才生成私钥文件内容复制过来
集成Jenkins-3
1.安装 mavan
在Jenkins集成服务器上,我们需要安装Maven来编译和打包项目。安装Maven
-
先上传Maven软件到服务器
tar -xzf apache-maven-3.6.2-bin.tar.gz
mkdir -p /opt/maven
mv apache-maven-3.6.2/* /opt/maven
vim /etc/pro?le
export JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk
export MAVEN_HOME=/opt/maven
export PATH=$PATH:$JAVA_HOME/bin:$MAVEN_HOME/bin
source /etc/pro?le
mvn -v
2.JK关联JDK和Maven
全局工具配置
Jenkins->Global Tool Con?guration->JDK->新增JDK,配置如下: 指定JDK的JAVA_HOME即可
同理指定MAVEN的MAVEM_HOME Jenkins->Global Tool Con?guration->Maven->新增Maven,配置如下:
添加Jenkins全局变量
Manage Jenkins->Con?gure System->Global Properties ,添加三个全局变量JAVA_HOME、M2_HOME、PATH+EXTRA
修改Maven的settings.xml
mkdir /root/repo
vi /opt/maven/conf/settings.xml
<mirror>
<id>alimaven</id>
<name>aliyun maven</name>
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
<mirrorOf>central</mirrorOf>
3.安装Pipeline、Maven Integration插件
Manage Jenkins->Manage Plugins->可选插件–>安装Pipeline、Maven Integration
三、Harbor安装
Harbor镜像服务器,安装在服务B器上
1.安装Docker并启动Docker,参考网上的安装过程
2.安装docker-compose
sudo curl -L https://github.com/docker/compose/releases/download/1.21.2/dockercompose-$(uname -s)-$(uname -m) -o /usr/local/bin/docker-compose
sudo chmod +x /usr/local/bin/docker-compose
3.给docker-compose 添加执行权限
sudo chmod +x /usr/local/bin/docker-compose
4.查看docker-compose是否安装成功
docker-compose -version
5.下载Harbor的压缩包 https://github.com/goharbor/harbor/releases
6.上传压缩包到linux,并解压
tar -xzf harbor-o?ine-installer-v1.9.2.tgz mkdir /opt/harbor
mv harbor/* /opt/harbor
cd /opt/harbor
7. 修改Harbor的配置
vi harbor.yml
修改hostname和port
hostname: 192.168.66.102
port: 85
8. 安装Harbor
./prepare
./install.sh
9.启动Harbor
docker-compose up -d 启动
docker-compose stop 停止
docker-compose restart 重新启动
10.访问Harbor http://192.168.66.102:85
默认账户密码:admin/Harbor12345
11.把Harbor地址加入到Docker信任列表(服务器A)
vi /etc/docker/daemon.json
{
"registry-mirrors": ["https://zydiol88.mirror.aliyuncs.com"],
"insecure-registries": ["192.168.66.102:85"]
}
需要重启Docker,同理,在部署的项目的服务器C中也要加入信任列表
四、创建流水线项目
1.创建任务,输入项目名称 并选着流水线
2.配置Git
配置->高级项目选项->流水香->Git
3.配置构建参数
4.编写Jenkins脚本
// git凭证id(在jenkins的全局凭证配置中可获取)
def git_auth = 'dff6b9f3-656f-4367-8e98-75f62572f1517'
// git 地址
def git_url = 'https://gitee.com/xiaoyu80453/awaesom-project.git'
//构建版本的名称
def tag = "latest"
//Harbor私服地址
def harbor_url = "xxx.55.94.99:9090"
//Harbor的项目名称
def harbor_project_name = "test"
//Harbor的凭证
def harbor_auth = "69eeec72-12648-4860-882f-f3425326c0a82"
node {
stage('拉取代码') {
echo '拉取代码'
checkout([$class: 'GitSCM',
branches: [[name: "*/${branch}"]],
extensions: [],
userRemoteConfigs: [[
credentialsId: "${git_auth}",
url: "${git_url}"
]]
])
}
stage('编译,构建镜像') {
//编译,构建本地镜像
sh "mvn clean package dockerfile:build" // 多了个dockerfile:build,就是激活插件生成镜像
}
stage('上传镜像') {
//定义镜像名称
def imageName = "${project_name}:${tag}"
//给镜像打标签
sh "docker tag ${imageName} ${harbor_url}/${harbor_project_name}/${imageName}"
//登录Harbor,并上传镜像
withCredentials([usernamePassword(
credentialsId: "${harbor_auth}",
passwordVariable: 'password', // 就是这样的,不用替换,在jk中配置的
usernameVariable: 'username')])
{
//登录
sh "docker login -u ${username} -p ${password} ${harbor_url}"
//上传镜像
sh "docker push ${harbor_url}/${harbor_project_name}/${imageName}"
echo "镜像上传成功"
}
//删除本地镜像
sh "docker rmi -f ${imageName}"
// 刪除打标签的镜像
sh "docker rmi -f ${harbor_url}/${harbor_project_name}/${imageName}"
//=====以下为远程调用进行项目部署========
sshPublisher(
publishers: [
sshPublisherDesc(
configName: '47.95.3.114',
transfers: [
sshTransfer(
cleanRemote: false,
excludes: '',
execCommand: "/opt/jenkins_shell/deploy.sh $harbor_url $harbor_project_name $project_name $tag $port",
execTimeout: 360000,
flatten: false,
makeEmptyDirs: false,
noDefaultExcludes: false,
patternSeparator: '[, ]+',
remoteDirectory: '',
remoteDirectorySDF: false,
removePrefix: '',
sourceFiles: ''
)],
usePromotionTimestamp: false,
useWorkspaceInPromotion: false,
verbose: false
)])
}
}
5. 选择脚本的位置所在
6.编写Dockerfiles文件
FROM openjdk:8-jdk-alpine
ARG JAR_FILE
COPY ${JAR_FILE} app.jar
EXPOSE 8080
ENTRYPOINT ["java","-jar","/app.jar"]
7.编写第四部中配置的deploy.sh
#! /bin/sh
harbor_url=$1
harbor_project_name=$2
project_name=$3
tag=$4
port=$5
imageName=$harbor_url/$harbor_project_name/$project_name:$tag
echo "$imageName"
containerId=`docker ps -a | grep -w ${project_name}:${tag} | awk '{print $1}'`
if [ "$containerId" != "" ] ; then
docker stop $containerId
docker rm $containerId
echo "成功删除容器"
fi
imageId=`docker images | grep -w $project_name | awk '{print $3}'`
if [ "$imageId" != "" ] ; then
docker rmi -f $imageId
echo "成功删除镜像"
fi
docker login -u eric -p Eric123456 $harbor_url
docker pull $imageName
docker run -di -p $port:$port $imageName
echo "容器启动成功"
8.配置构建触发器
因为我用的是Giee,所以额外安装了Gitee Plugin 插件 随后将上图的url和Gitee WebHook 密码配置到码云的**webHook **中即可
9. 配置服务器B跟服务器C免密连接
上面所述的远程调用(jk调用部署服务器)是需要公钥私钥的
1)从服务器A拷贝公钥到远程服务器C(部署服务器)
2)系统配置->添加远程服务器
以上整个流程没毛病,但是连不上250服务器就很让人困惑了, 最后在jenkins官网的issue上看到解决方案 先说明问题原因,因为新版本的生成秘钥方式插件暂时还不支持,所以就用老方式来生成秘钥吧: 修改Jenkins?le构建脚本生成远程调用模板代码
rm -rf /root/.ssh/*
ssh-keygen -t rsa -b 4096 -m PEM
ssh-copy-id 192.168.88.250
10.大体流程配置结束
五、创建流水线项目
1.正常创建好任务(流水线)
2. 直接写脚本
//gitlab的凭证
def git_auth="dff63b9f3-656f-4367-8e98-75f624572f157"
node{
stage('拉取代码'){
checkout([
$class: 'GitSCM',
branches: [ [ name: '*/${branch}' ]],
doGenerateSubmoduleConfigurations: false,
extensions: [ ],
submoduleCfg: [ ],
userRemoteConfigs: [
[
credentialsId: "${git_auth}",
url: 'https://gitee.com/xi4ao6yu8503/awaesom-project-front.git'
]
]
])
}
stage('删除原文件'){
//=====以下为远程调用进行项目部署========
sshPublisher(publishers: [
sshPublisherDesc(
configName: '147.95.3.114',
transfers: [
sshTransfer(cleanRemote: false,
excludes: '',
execCommand: 'rm -rf /home/www/hexo/*',
execTimeout: 360000,
flatten: false,
makeEmptyDirs: false,
noDefaultExcludes: false,
patternSeparator: '[,]+',
remoteDirectory: '',
remoteDirectorySDF: false,
removePrefix: '',
sourceFiles: '')
],
usePromotionTimestamp: false,
useWorkspaceInPromotion: false,
verbose: false)
])
}
stage('打包,部署网站'){
//使用NodeJS的npm进行打包
nodejs('nodejs14'){
sh '''
npm install
npm run build
'''
}
//=====以下为远程调用进行项目部署========
sshPublisher(publishers: [
sshPublisherDesc(
configName: '147.95.23.114',
transfers: [
sshTransfer(cleanRemote: false,
excludes: '',
execCommand: '',
execTimeout: 360000,
flatten: false,
makeEmptyDirs: false,
noDefaultExcludes: false,
patternSeparator: '[,]+',
remoteDirectory: '/home/www/hexo',
remoteDirectorySDF: false,
removePrefix: 'dist',
sourceFiles: 'dist/**')
],
usePromotionTimestamp: false,
useWorkspaceInPromotion: false,
verbose: false)
])
}
}
3. 在项目中编写Jenkins文件
/* groovylint-disable CompileStatic, DuplicateStringLiteral, GStringExpressionWithinString, Indentation, LineLength, NoDef, TrailingWhitespace, UnusedVariable, VariableName, VariableTypeRequired, vscode忽略警告提示 CompileStatic */
//gitlab的凭证
def git_auth = 'dff6b9f3-65f-4367-8e98-752572f157'
// git 地址
def git_url = 'https://gitee.com/xiyu8/awaesom-project-front.git'
//Harbor私服地址
def harbor_url = '10.55.94.9:9090'
//前端项目名称
def project_name = 'fronttest'
//构建版本的名称
def tag = 'latest'
//Harbor的项目名称
def harbor_project_name = 'test'
//Harbor的凭证
def harbor_auth = '69eeec72-1648-48-882f-f3425c0a82'
//定义镜像名称
def imageName = "${project_name}:${tag}"
node {
stage('拉取代码') {
checkout([
$class: 'GitSCM',
branches: [ [ name: '*/${branch}' ]],
doGenerateSubmoduleConfigurations: false,
extensions: [ ],
submoduleCfg: [ ],
userRemoteConfigs: [
[
credentialsId: "${git_auth}",
url: "${git_url}"
]
]
])
}
stage('编译,构建镜像') {
//编译,构建本地镜像
sh "docker build -t ${project_name} . "
//给镜像打标签
sh "docker tag ${imageName} ${harbor_url}/${harbor_project_name}/${imageName}"
}
stage('上传镜像') {
//登录Harbor,并上传镜像
withCredentials([usernamePassword(
credentialsId: "${harbor_auth}",
passwordVariable: 'password', // 就是这样的,不用替换,在jk中配置的
usernameVariable: 'username')])
{
//登录
sh "docker login -u ${username} -p ${password} ${harbor_url}"
//上传镜像
sh "docker push ${harbor_url}/${harbor_project_name}/${imageName}"
echo '镜像上传成功'
}
//删除本地镜像
sh "docker rmi -f ${imageName}"
// 刪除打标签的镜像
sh "docker rmi -f ${harbor_url}/${harbor_project_name}/${imageName}"
//=====以下为远程调用进行项目部署========
sshPublisher(
publishers: [
sshPublisherDesc(
configName: '4.9.83.169',
transfers: [
sshTransfer(
cleanRemote: false,
excludes: '',
execCommand: "/opt/jenkins_shell/deployfront.sh $harbor_url $harbor_project_name $project_name $tag $port",
execTimeout: 360000,
flatten: false,
makeEmptyDirs: false,
noDefaultExcludes: false,
patternSeparator: '[, ]+',
remoteDirectory: '',
remoteDirectorySDF: false,
removePrefix: '',
sourceFiles: ''
)],
usePromotionTimestamp: false,
useWorkspaceInPromotion: false,
verbose: false
)])
}
}
4.项目中编写Dockerfile文件
FROM nginx
ADD ./dist /usr/share/nginx/html/
COPY nginx.conf /etc/nginx/conf.d/
EXPOSE 9000
RUN echo 'build ok'
5.步骤4中的deployfront.sh
#! /bin/sh
harbor_url=$1
harbor_project_name=$2
project_name=$3
tag=$4
port=$5
imageName=$harbor_url/$harbor_project_name/$project_name:$tag
echo "$imageName"
containerId=`docker ps -a | grep -w ${project_name}:${tag} | awk '{print $1}'`
if [ "$containerId" != "" ] ; then
docker stop $containerId
docker rm $containerId
echo "成功删除容器"
fi
imageId=`docker images | grep -w $project_name | awk '{print $3}'`
if [ "$imageId" != "" ] ; then
docker rmi -f $imageId
echo "成功删除镜像"
fi
docker login -u eric -p Eric123456 $harbor_url
docker pull $imageName
docker run -di -p $port:80 $imageName
echo "容器启动成功"
3.大体流程配置结束
|