There are several ways to add a service to auto-start on Linux
Published on Aug. 22, 2023, 12:14 p.m.
There are several ways to add a service to auto-start on Linux, depending on the system’s init system. Here are some common methods:
System V (sysvinit)
Find the appropriate init script for the service in the /etc/init.d/ directory.
Use the update-rc.d command to add the service to the desired runlevels. For example, to add myservice to runlevels 2, 3, 4 and 5: sudo update-rc.d myservice defaults 2345
Upstart
Create a .conf file in the /etc/init/ directory that describes the service. For example: sudo nano /etc/init/myservice.conf
Add the appropriate directives to the file. Here is an example:
description "My Service"
start on runlevel [2345]
stop on runlevel [!2345]
exec /usr/bin/myservice --daemon
Use the initctl command to control the service. For example, to start the service: sudo initctl start myservice
systemd
Create a .service file in the /etc/systemd/system/ directory that describes the service. For example: sudo nano /etc/systemd/system/myservice.service
Add the appropriate directives to the file. Here is an example:
[Unit]
Description=My Service
After=network.target
[Service]
ExecStart=/usr/bin/myservice --daemon
Type=simple
[Install]
WantedBy=multi-user.target
Use the systemctl command to control the service. For example, to start the service: sudo systemctl start myservice
It’s important to note that while these are the common methods, your system may have a different init system and require a different approach.
using cron
While using cron is not the most common method for autostarting a service in Linux, it is possible to use it to achieve the desired result. Here’s how you can do it:
Create a shell script that starts the service. For example, myservice.sh:
#!/bin/bash
service myservice start
Make the script executable: chmod +x myservice.sh
Edit the cron table using crontab -e.
Add the following line to the bottom of the file to run your script at startup:
@reboot /path/to/myservice.sh
This will start your service every time the system is rebooted.
It’s worth noting that this approach is not as robust as using a dedicated init system like System V, Upstart, or systemd. If your cron job fails, there may not be a way to handle it gracefully. Therefore, it’s recommended to use a more appropriate approach depending on your Linux distribution and init system