如何在 jenkins pipeline 中使用 Jenkinsfile 部署 Java war 文件



在 Jenkins maven 项目中,我们可以使用BUILD_ID=DontKillMe来防止 Hudson 脚本关闭 shell 调用。

喜欢:BUILD_ID=DontKillMe java -jar target.jar

但是添加BUILD_IDJenkinsfile中不起作用.


詹金斯文件:

#!/usr/bin/env groovy
node {
stage('Build') {
checkout scm
sh '/opt/gradle/gradle-4.1/bin/gradle clean build'
}
stage('Deploy') {
sh 'mkdir -p /opt/www/foobar'
sh 'cp build/libs/*.war /opt/www/foobar/newest.war'
sh 'chmod 755 ./deploy.sh'
sh 'nohup ./deploy.sh &'
sh 'while ! httping -qc1 http://localhost:10000 ; do sleep 1 ; done'
}
}

哈德逊脚本执行后,哈德逊脚本调用的所有 shell 都将关闭。即使是双nohup仍然不起作用。

deploy.sh:

#!/bin/bash
nohup java -jar -Dspring.profiles.active=prod /opt/www/foobar/newest.war /var/log/foobar.log 2>&1 &

您可以在sh步骤中以相同的方式使用BUILD_ID=dontKillMe

sh 'BUILD_ID=dontKillMe nohup ./deploy.sh &'

我找到了另一种执行脚本的方法,不能被杀死。

  • Linux服务

/etc/init.d/www-project

#!/bin/bash
. /etc/init.d/functions
SERVICE_NAME="www-project"
RETVAL=0
PID=-1
PIDFILE=/var/run/${SERVICE_NAME}.PID
start () {
if [ -f ${PIDFILE} ]; then
echo "PID file ${PIDFILE} already exists, please stop the service !"
exit
fi
echo "Starting service ${SERVICE_NAME} ..."
java -jar -Dspring.profiles.active=prod /opt/www/project/newest.war > /var/log/www-project.log 2>&1 &
PID = $!  
if [ -z ${PID} ]; then 
echo "Failed to get the process id, exit!"
exit
else
echo "Starting successfully, whose pid is ${PID}"
fi
touch $PIDFILE
echo ${PID} > ${PIDFILE}
}
stop () {
if [ -f $PIDFILE ]; then 
PID = `cat ${PIDFILE}`
if [ -z $PID ]; then 
echo "PIDFILE $PIDFILE is empty!"
exit
fi
if [ -z "`ps axf | grep $PID | grep -v grep`" ]; then
echo "Process dead but pidfile exists!"
exit
else
kill -9 $PID
echo "Stopping service successfully, whose pid is $PID"
rm -f $PIDFILE
fi
else
echo "File $PIDFILE does NOT exist!"
fi
}
restart () {
stop
start
}
status () {
if [ -f $PIDFILE ]; then
PID=`cat $PIDFILE`
if [ -z $PID ] ; then
echo "No effective pid but pidfile exists!"
else
if [ -z "`ps axf | grep $PID | grep -v grep`" ]; then
echo "Process dead but pidfile exist"
else
echo "Running"
fi
fi
else
echo "Service not running"
fi
}
case "$1" in
start)
start
;;
stop)
stop
;;
restart)
restart
;;
status)
status
;;
*)
echo "Usage: www-project {start|stop|restart|status}"
;;
esac
  • 系统单元服务

/usr/lib/systemd/system/www-project.service

[Unit]
Description=project
After=mysqld.service
Wants=mysqld.service
[Service]
ExecStart=/usr/lib/jvm/java/bin/java -jar -Dspring.profiles.active=prod /opt/www/project/newest.war > /var/log/www-project.log
PIDFile=/var/run/www-project.pid
ExecReload=/bin/kill -HUP $MAINPID
ExecStop=/bin/kill -9 $MAINPID
[Install]
WantedBy=multi-user.target

在 Jenkinsfile 中,我们可以调用

service restart www-project

systemctl restart www-project

哈德逊脚本永远不会杀死服务。

最新更新