Ubuntu: Run Script on startup on AWS Ec2 Ubuntu 1404 Server



Question:

I Need to start services such as elasticsearch, kafka on boot time of the Ec2 instance

I Have tried @reboot on crontab but something is going wrong

Shell Script:

#!/bin/sh    nohup /home/ubuntu/elasticsearch-2.3.4/bin/elasticsearch &  

Crontab entry:

@reboot sh /home/abhijeet/startServices.sh  

I dont know where I am going wrong


Solution:1

cron runs shells in a modified environment with a minimal PATH and presumably /usr/bin not present there so /usr/bin/nohup is not being found.

You can:

  • add /usr/bin to the PATH, rather than modifying your crontab's one, you should add this at the top of the script:

    #!/bin/sh  export PATH="$PATH":/usr/bin  nohup /home/ubuntu/elasticsearch-2.3.4/bin/elasticsearch &  
  • Use absolute path to nohup:

    #!/bin/sh  /usr/bin/nohup /home/ubuntu/elasticsearch-2.3.4/bin/elasticsearch &  

Note that, according to the crontab entry, you are executing the script as an argument to sh (dash) while having an exactly same shebang. In this case this doesn't make any difference but be careful about this if the shebang is different. Usually one would make the script executable and use shebang to indicate the desired interpreter.


Now, the most important part. cron runs all given jobs in their respective subshells and spawns these subshell parallel (non-blocking) i.e. runs jobs in parallel manner. So you don't need the nohup and backgrounding (&), just do (based on your example, /home/ubuntu/elasticsearch-2.3.4/bin/elasticsearch is executable):

@reboot /home/ubuntu/elasticsearch-2.3.4/bin/elasticsearch  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »