I have a Java Spring Boot application. I managed to build and deploy jar using pipeline on push to master. But the pipeline doesn't detach and runs indefinitely because it gets attached to running java app. Below is my setup.
bitbucket-pipelines.yml:
image: maven:3.8.3-openjdk-11
pipelines:
default:
- step:
name: Build and Deployment
caches:
- maven
script:
- echo "Building..."
- mvn clean package
- echo "Deploying to production"
- scp target/app.jar <user>@<hostname>:/home/user/
- pipe: atlassian/ssh-run:0.8.0
variables:
SSH_USER: '<user>'
SERVER: '<hostname>'
COMMAND: '/home/user/run.sh'
run.sh
#!/bin/sh
cd /home/user
# Specify the name of the Java process
PROCESS_NAME="app.jar"
# Find the PID of the Java process
PID=$(pgrep -f "$PROCESS_NAME")
if [ -n "$PID" ]; then
echo "Stopping Java process: $PROCESS_NAME (PID: $PID)"
kill -15 "$PID"
# Wait for the process to terminate
while kill -0 "$PID" 2> /dev/null; do
sleep 1
done
echo "Java process stopped."
else
echo "Java process $PROCESS_NAME not found."
fi
# replace jar
mv app.jar currently_running_build/
# run app
nohup java -jar currently_running_build/app.jar application.yml &
I played with several things (and combinations). None of them helped me yet.
- adding explicit
exit 0in the end of shell script. - disown
- setting
MODE: 'script'in bitbucket-pipelines - adding wrapping shell script which will trigger run.sh and detach
- setting command as
nohup /home/user/run.sh &yielded to application stopped, not detached
If you have any working ideas, I would highly appreciate your advice. Of course I can either stop pipeline manually or remove the final step and do it manually on remote machine. Both way works, but I want to reduce manual work here.
Your life would be easier if you wrote service unit for systemd. All that script you are writing is a reimplementation of a feature subset from systemd, which is most probably already featured in your server.
Check How do I run a node.js app as a background service? for an example with node.js, but a java example will boil down to something very similar. Check the docs to see all the bells and whistles that you can use.
Then, in your pipeline just restart the service unit.