Sometimes it might be required to run scripts at startup in Linux servers. On many High Availability VPS platforms, you can use Cloud-init to run scripts at start-up. However, some systems don’t have access to Cloud-init. In this guide, we will create a start-up service and script to run when your server boots. This is useful if you want to automate tasks like running updates, installing packages or even setting static routes to the gateway. Here we will create a new service and invoke a custom bash script to set static routes in a VPS. Your script can do anything as long as it’s bash and coded correctly. First, we will create a new service. Our service will be called f2h.service. You can name your server anything but it must end .service.
Most Linux distributions use systemd to manage services so this is an excellent and easy way to configure custom functions. Systemd manages startup functions and does important things like raising network interfaces. It’s present in all of the major OS distributions by default so requires very little configuration by end-users. We’re going to create a new service in the next steps and code a simple script to run at startup.
Create Startup Service
System services are usually located in /etc/systemd/system/ We are using an Ubuntu NVMe VPS but the same is true for Debian and CentOS. Create a new file with your service name and enter the code.
nano <em>/etc/systemd/system/</em>f2h.service
[Unit]
After=cloud-init.service
[Service]
ExecStart=/F2H/routes.sh
[Install]
WantedBy=default.target
Unit = This area stipulates when our custom bash script will be run. So, our script is set to run after Cloud-init. You can switch this to a different service like the networking.service if required.
Service = This is the path to our bash script
Install = This is the target the service is installed to. But, do not edit this.
Now chmod the file 664
chmod 664 /etc/systemd/system/f2h.service
Create Bash Script
So, this is the file that will contain our script. The location of our script is going to be /F2H/routes.sh as specified in the service file above.
nano /F2H/routes.sh
#!/bin/bash
ip route add 10.10.10.1 dev eth0
ip route add default via 10.10.10.1
This script configures a static route to our internal gateway. Your script can do anything you want. Now chmod the file 744.
chmod 744 /F2H/routes.sh
Reload Services
Finally, we reload the daemon and enable our new service.
systemctl daemon-reload
systemctl enable f2h.service
That’s it. You can now run custom scripts at startup in your Linux Server.