Autostarting scripts on startup in ubuntu

  • Let us say you want to run a script whenever your machine starts or restarts. This script might start any other program/software.
  • In my case, I have a script that I want to run and it’s path is /home/ubuntu/serverstart.sh. This script simply starts a python server. To make sure that this script is always triggered after a restart or a shutdown, a service needs to be created.

Steps

  1. Create a file named serverstart.service and put it in the /etc/systemd/system with the following contents

    [Unit]
    Description=Starts the server
    After=network.target
    StartLimitIntervalSec=0
    
    [Service]
    Type=simple
    Restart=always
    RestartSec=1
    User=ubuntu
    ExecStart=/bin/bash /home/ubuntu/serverstart.sh
    
    [Install]
    WantedBy=multi-user.target
    
  2. Here the ExecStart is the path of any script that we want to execute should be placed and since we want to trigger

  3. After the file is placed in the path /etc/systemd/system, one can start it by doing sudo systemctl start serverstart

  4. To make it autostart in the boot, sudo systemctl enable serverstart

This was tested on an AWS EC2 instance with Ubuntu 18.04.3