Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to run nohup command from jenkins as a background process

UPDATE: Based on below discussion I have edited my answer for more accurate description.

I am trying to run a nohup command from jenkins. The full command is

nohup java -jar /home/.../jar/server-process-0.35.jar prod >> /var/../server-process-prod.log 2>&1 &

This command does not work. I can see status as success in jenkins but no java process in linux. When I do 'ps -ef | grep java'

However when I remove the last '&' , that is I change it from run in forground instead of background

It starts working. I can see the java process started.

The original command works fine If I run it on linux console.

I need to run it from jenkins in the original form that is as a backgorund process. So that it is independant of jenkins.

Any clues why is this happening?

like image 356
Utsav Gupta Avatar asked May 20 '16 08:05

Utsav Gupta


People also ask

How do I run nohup in the background?

To run a nohup command in the background, add an & (ampersand) to the end of the command. If the standard error is displayed on the terminal and if the standard output is neither displayed on the terminal, nor sent to the output file specified by the user (the default output file is nohup. out), both the ./nohup.

How does nohup check background process?

Run ping command with nohup command. Re-open the terminal and run pgrep command again. You will get the list of the process with process id which is running. You can stop any background process by running kill command.

Can we use nohup in shell script?

Nohup command prevents the process from receiving this signal upon closing or exiting the terminal/shell. Once a job is started or executed using the nohup command, stdin will not be available to the user and nohup. out file is used as the default file for stdout and stderr.

Do you need ampersand with nohup?

The answer is the same as usual - it depends. nohup catches the hangup signal while the ampersand does not.


2 Answers

Long story short, Jenkins kills all processes spawned by a job once that job finishes. To override this behavior, you need to set an environment variable.

The variable appears to vary from job type to job type. It used to be BUILD_ID, but for Pipeline jobs it is JENKINS_NODE_COOKIE, and there are several others mentioned in this answer.

So if you're running your command in Pipeline, it would look like this:

sh 'JENKINS_NODE_COOKIE=dontKillMe nohup java -jar /home/.../jar/server-process-0.35.jar prod >> /var/../server-process-prod.log 2>&1 &'

See the wiki on ProcessTreeKiller and this comment in the Jenkins Jira for more information.

like image 182
jpyams Avatar answered Oct 21 '22 17:10

jpyams


In your jenkins shell script try:

  export BUILD_ID=dontKillMe
  nohup java -jar your_java_app.jar &

It worked for me!

like image 7
Joao Vitor Marques Avatar answered Oct 21 '22 15:10

Joao Vitor Marques