Search code examples
linuxubuntu-16.04vpsrestartreboot

Autostart script on vps reboot?


I have a vps linux ubuntu 16.04 with some server installed.

I'm tired of manually restarting my server all the time. What can I do solve this problem?

My servers run with a "screen"

All time when i need to restart a server i need do this:

  1. (Open the screen) < Screen -r "ScreenName" >
  2. (Go inside the folder) < cd /home/server/ >
  3. (Start the server) < ./server.sh >
  4. (Close the screen) < ctrl a+d >

There is a way to perform all these steps automatically when restarting the server?

Thanks.


Solution

  • What I do is I have a file called onboot.sh in my home directory. Contents of that file would be:

    #!/bin/bash
    cd /home/server
    screen -Ldm -S ScreenSessionName bash server.sh
    

    The L is optional. It will create a file called screenlog.0 in the directory containing the log of the script's output. -S Sets the sessionnname. -d detaches the screen once it's been created and -m enforces to create a new screen session.

    For the script to be run on boot I use cron. In my case I use sudo crontab -e to edit the root user's crontab and append the following line:

    @reboot sudo -u username bash /home/username/onboot.sh
    

    That will run the onboot.sh as the given user. If you want it to be run as root you can simply put

    @reboot bash /home/username/onboot.sh
    

    Inside the crontab.


    Quicker approach if you need just that one script:

    Execute crontab -e as the user you want the server.sh script to be run as.

    Append the following line:

    @reboot cd /home/server && screen -Ldm -S ScreenSessionName bash server.sh
    

    Save the file. That's it.