Autostart Services with Systemd in Linux
Before getting started, it's recommended that you have a basic idea of what's actually going on by reading this awesome page on the Arch Wiki.
The command we want to run is:
/apps/myapp/executable
where /apps/myapp
is the directory and executable
is the name of the binary that we want to execute.
Preparations
Using your user account (Not Recommended)
If you're running the service using your existing user account, follow these steps:
-
Get your username by running:
id -un
-
Find your group name by running:
id -gn
-
For detailed user and group information, run:
id
Example output:
uid=1000(username) gid=1000(groupname) groups=1000(groupname),27(sudo),100(users)
Here,
username
is your username, andgroupname
aftergid=
is your primary group name.
Creating a Separate User and Group (Recommended)
For better security, it's recommended to create a separate user and group to run the service. This ensures the service is isolated from your main user account.
To create a new user and group:
-
Create a new group:
sudo groupadd servicegroup
-
Create a new user with no login shell and assign it to the group:
sudo useradd -r -s /usr/sbin/nologin -g servicegroup serviceuser
-r
: Creates a system user.-s /usr/sbin/nologin
: Ensures the user cannot log in.-g servicegroup
: Assigns the user to the specified group.
-
Ensure the user and group have the necessary permissions for the application directory:
sudo chown -R serviceuser:servicegroup /apps/myapp
Ensure that the user running the service has the necessary permissions to access the application directory and any configuration files or resources it depends on.
Creating a Systemd Service File
-
Create a systemd service file:
sudo nano /etc/systemd/system/myapp.service
Replace
myapp
with the desired name for the service. -
Add the following content:
[Unit]
Description=MyApp Service
After=network.target
[Service]
ExecStart=/apps/myapp/executable args --config arg2
WorkingDirectory=/apps/myapp
Restart=always
User=serviceuser
Group=servicegroup
[Install]
WantedBy=multi-user.targetReplace the following placeholders:
ExecStart
: Full path to your executable with any required arguments.WorkingDirectory
: Directory where your application resides.User
: The user running the service.Group
: The group running the service.- For more details, refer to the systemd.service documentation's OPTIONS section.
-
Save and close the file.
Enabling and Starting the Service
-
Reload systemd to recognize the new service:
sudo systemctl daemon-reload
-
Enable the service to start on boot:
sudo systemctl enable myapp
-
Start the service immediately:
sudo systemctl start myapp
-
Verify the service is running:
sudo systemctl status myapp
Viewing Logs
To view logs for the service in real-time, run:
journalctl -u myapp -f
Make sure to test the service thoroughly to confirm it behaves as expected both during manual starts and after a system reboot.