第一步,jenkins基础环境搭建
1,安装jenkins
docker run -d --name jenkins -p 80:8080 -p 50000:50000 -u root \
-v /opt/jenkins_home:/var/jenkins_home \
-v /var/run/docker.sock:/var/run/docker.sock \
-v /usr/bin/docker:/usr/bin/docker \
-v /usr/local/maven:/usr/local/maven \
-v /usr/local/jdk:/usr/local/jdk \
-v /etc/localtime:/etc/localtime \
--name jenkins jenkins/jenkins:lts
2.选择插件安装,不安装任何插件,后面我们会替换源,推荐安装,经常出现安装错误,因为源是国外的
4,替换jenkins的配置文件的源
修改国内源:
cd /opt/jenkins_home/updates
sed -i 's/http:\/\/updates.jenkins-ci.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
然后重启jenkins容器生效。
5,安装插件 Git 和 Pipeline
6.配置git和harbor 的凭证
二,创建一个golang的项目
2.1 传入pipeline的参数Branch函数,master分支,‘发布代码分支’注释
2.2,写pipeline脚本
#!/usr/bin/env groovy
def registry = "10.1.1.11"
def project = "datacenter"
def app_name = "zhiyuecms"
def image_name = "${registry}/${project}/${app_name}:${Branch}-${BUILD_NUMBER}"
def git_address = "http://10.1.1.11:9999/golang/zhiyuecms.git"
def docker_registry_auth = "e94b8182-3024-42be-945b-1c6e3616e337"
def git_auth = "be4bef32-d981-489b-bf5c-fc85fe5eff71"
pipeline {
agent any
stages {
stage('拉取代码'){
steps {
checkout([$class: 'GitSCM', branches: [[name: '${Branch}']], userRemoteConfigs: [[credentialsId: "${git_auth}", url: "${git_address}"]]])
}
}
stage('构建镜像'){
steps {
withCredentials([usernamePassword(credentialsId: "${docker_registry_auth}", passwordVariable: 'password', usernameVariable: 'username')]) {
sh """
echo '
FROM golang:1.12 as build
ENV GOPROXY https://goproxy.io
ENV GO111MODULE on
WORKDIR /go/cache
ADD go.mod .
RUN go mod tidy
RUN go mod download
WORKDIR /go/release
ADD . .
RUN GOOS=linux CGO_ENABLED=0 go build -ldflags="-s -w" -installsuffix cgo -o grpcswagger main.go
FROM scratch as prod
COPY --from=build /usr/share/zoneinfo/Asia/Shanghai /usr/share/zoneinfo/Asia/Shanghai
COPY --from=build /go/release/grpcswagger /
CMD ["/grpcswagger"]
' > Dockerfile
docker build -t ${image_name} .
docker login -u ${username} -p '${password}' ${registry}
docker push ${image_name}
"""
}
}
}
stage('部署到Docker'){
steps {
sh """
REPOSITORY=${image_name}
docker rm -f zhiyuecms |true
docker container run -d -p 10004:10004 --net=host --restart=always -e ASPNETCORE_ENVIRONMENT='Staging' -v /config/zhiyuecms/appsetting.toml:/appsetting.toml -v /config/zhiyuecms/rsa_1024_priv.pem:/rsa_1024_priv.pem -v /config/zhiyuecms/rsa_1024_pub.pem:/rsa_1024_pub.pem -v /config/zhiyuecms/apiclient_cert.p12:/apiclient_cert.p12 --name zhiyuecms ${image_name}
"""
}
}
}
}