Logo ← PostgreSQL Blog

Understanding and creating linux service

Creating a Linux service allows you to run a program or script as a background process that starts automatically when your system boots up…

Understanding and creating linux service

Creating a Linux service allows you to run a program or script as a background process that starts automatically when your system boots up. This article will guide you through the process of creating a service using systemd, a system and service manager for Linux.

Prerequisites

Before you begin, ensure that you have:

  • A user account with sudo privileges.
  • The program or script you want to run as a service.

Steps to Create a Linux Service

1. Create the Service File

Create a new service file ending with .service in the /etc/systemd/system/ directory. For example, let's create a service for a simple Python script named myscript.py.

sudo nano /etc/systemd/system/myscript.service

2. Add Service Configuration

Paste the following content into the myscript.service file:

[Unit]
Description=My Custom Service
After=network.target

[Service]
ExecStart=/usr/bin/python3 /path/to/myscript.py
Restart=always
User=username
[Install]
WantedBy=multi-user.target

Replace /path/to/myscript.py with the actual path to your script and username with your username.

  • Description: A brief description of the service.
  • After: Indicates that the service should start after the network is up.
  • ExecStart: Command to execute when the service starts.
  • Restart: Defines the restart behavior.
  • User: Specifies the user under which the service should run.
  • WantedBy: Specifies when the service should be started.

3. Reload systemd

After creating the service file, reload the systemd manager configuration to recognize the new service.

sudo systemctl daemon-reload

4. Enable and Start the Service

Enable the service to start on boot and then start the service.

sudo systemctl enable myscript.service
sudo systemctl start myscript.service

5. Check the Service Status

Check the status of your service to ensure it’s running without any issues.

sudo systemctl status myscript.service

Conclusion

You’ve successfully created a Linux service using systemd! Your script will now run as a background service, starting automatically when the system boots up. You can manage the service using systemctl commands like start, stop, restart, enable, and disable.

Remember to replace the paths and commands with your actual script and configurations. Make sure to test your service thoroughly to ensure it behaves as expected.