3

Here I have an application deployed to linux, I want the app to startup automatically when the linux start up. I'm using an command like 'sudo ./start' to start the application. How Can I do that?

OS: CentOS 6

3 Answers 3

8

I cannot recommend to add things in /etc/rc.local. It's a relict of old unix days. There are Linuxes who no longer support rc.local.

However, It may start your application/service correctly, but it never shuts your process down gracefully.

It's better to use the systems own mechanism of init scripts (Systemd, Upstart, ...). I would write an rc script that looks like this (there might be a skeleton/template on your system in /etc/init.d/skeleton):

#!/bin/bash
. /etc/init.d/functions

start() {
        echo -n "Starting <servicename>: "
        #/path/to/the/executable/of/your/application
}

stop() {
        echo -n "Shutting down <servicename>: "
        #command_to_gracefully_end_the_application
}

case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    status)
    #command_to_report_the_status
    ;;
    restart)
        stop
        start
        ;;
    *)
        echo "Usage: <servicename> {start|stop|restart}"
        exit 1
        ;;
esac
exit $?

Place your script in /etc/init.d/, make it executable and add it to the system runlevels 3, 4 and 5:

chkconfig --level 345 <servicename> on

Also you can manually start and stop it with:

service <servicename> start
service <servicename> stop
3
  • It's a good idea to write a script like this, can I can manually start and stop. but when reboot my computer, the application cannot start up. why? Aug 29, 2014 at 7:36
  • I've resolved this issue after clueless tries. Aug 29, 2014 at 8:04
  • It seems that to make the file supported by chkconfig, a few additional lines of comments need to be added: serverfault.com/questions/29788/…
    – xji
    Sep 6, 2018 at 13:52
2

Most Linuxes out there run /etc/rc.local once at system boot-up. Open this file with an editor and add the command to start your application.

No need to prefix sudo to the command as the script is run as root.

Be sure to add a '&` (ampersand) at the end of the command to run it in the background so it doesn't hold up your system from booting in case your application doesn't finish in one go.

Example to execute the file myscript located in /usr/local/bin/

# place near the end of /etc/rc.local
/usr/local/bin/myscript &
0

Using cron worked for me.

# enter crontab edit
crontab -e

# place this inside the cron file you opened with the previous command
@reboot /path/to/your/script.sh

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .