How to Create a Systemd Service in Linux? [11 Proven Steps]

Written by

Reviewed by

Last updated: June 17, 2024

Expert verified

SVG Image

TL;DR

To learn how to create a systemd service in Linux, follow these steps:

  1. Create a new systemd service file with your chosen name: sudo touch your_service.service.
  2. Open the newly created service file in a text editor to input service details: sudo nano your_service.service.
  3. Reload the systemd manager configuration to recognize the new service: sudo systemctl daemon-reload.
  4. Enable the service to start at boot, then immediately start it: sudo systemctl enable your_service.service && sudo systemctl start your_service.service.
  5. Verify the service is running properly and view its status: sudo systemctl status your_service.service.

Managing Linux system processes efficiently can seem challenging, especially when you’re trying to ensure critical applications run without a hitch or automate tasks to start at boot. Creating a systemd service is a great way to simplify this task. In this post, you will learn how to create a systemd service in Linux.

You’ll get easy-to-follow steps, tips for avoiding common errors, and ways to keep your services running smoothly. By the end, you’ll know how to set up reliable services that start at boot and restart if they crash. You’ll also learn how to handle dependencies and manage logs for better troubleshooting. Whether you’re new to systemd or want to improve your skills, this guide will help you master Linux service management.

What is a systemd Service in Linux?

A systemd service is a configuration unit that describes how to manage a service or application under the systemd system and service manager. Systemd is a suite of basic building blocks for a Linux system, and it is the most widely used init system on modern Linux distributions.

Key points about systemd services:

  • Definition: A systemd service is defined in a configuration file with a .service extension, typically located in the /etc/systemd/system/ or /usr/lib/systemd/system/ directories.
  • Service management: Systemd services can be started, stopped, restarted, and queried using the systemctl command.
  • Dependency management: Services can specify dependencies on other services or system states, ensuring that services start in the correct order and with the necessary resources available.
  • Process tracking: Systemd can track the processes associated with a service, allowing it to restart the service if it crashes or terminate the processes when the service is stopped.
  • Resource management: Systemd can control service resource utilization, such as CPU and memory usage, to prevent resource starvation or overutilization.
  • Logging: Systemd captures and manages log messages generated by services, making it easier to diagnose issues.

A basic systemd service file consists of three main sections:

  1. [Unit]: Contains metadata about the service, such as its description and dependencies.
  2. [Service]: Defines the command to start the service, the type of service (simple, forking, oneshot, etc.), and other service-specific configurations.
  3. [Install]: Specifies when and how the service should be enabled, such as at system boot or on-demand.

Systemd services provide a standardized and efficient way to manage services on a Linux system, simplifying service administration and improving system reliability.

How to Create a systemd Service in Linux?

To create systemd service in Linux, start by opening your terminal and navigating to the /etc/systemd/system/ directory. Linux create service file using sudo touch your_service.service. Edit the file with your preferred text editor, adding sections for [Unit], [Service], and [Install], specifying details like the service description, the command to run, and any dependencies.

Save and exit the editor, then reload systemd with sudo systemctl daemon-reload. Enable your service to start on boot with sudo systemctl enable your_service.service and start it immediately with sudo systemctl start your_service.service. Check its status using sudo systemctl status your_service.service.

That was the quick answer. Here is the detailed step-by-step guide to Linux create service:

  1. Open your Terminal by pressing Ctrl + Alt + T.
open terminal
  1. Navigate to the systemd directory by running the command: 
cd /etc/systemd/system/

This is where all service files are stored.

navigating to systemd directory
  1. Linux create service file by typing the following command:
sudo touch your_service.service

Replace your_service with the name you wish to give your service. Enter password of prompted.

creating a new service file
  1. Use your preferred text editor to edit your service file. Here, I’ll use nano.
sudo nano your_service.service

It will open the newly created service file in the nano text editor for editing.

opening service file with nano editor
  1. In the editor, populate your service file with the following structure. Adjust the ExecStart, Description, and other directives according to your needs.
[Unit]
Description=Your Service Description
After=network.target
[Service]
ExecStart=/path/to/your/script
User=root
Restart=always
RestartSec=3
[Install]
WantedBy=multi-user.target
  • Description: A brief description of your service.
  • After: Specifies that your service should start after the network is ready.
  • ExecStart: The command or script your service will run.
  • User: The user under which the service will run. This is root by default.
  • Restart: Configures whether and how the service should be restarted if it exits.
  • RestartSec: The time to wait before restarting a service.
  • WantedBy: Defines the target that the service should be attached to.
editing service file in nano editor
  1. Save and exit the editor. Press Ctrl+O, Enter to save, and Ctrl+X to exit. This saves the configuration you’ve just entered into the service file.
  2. After saving your service file, reload systemd to ensure it recognizes your new service.
sudo systemctl daemon-reload

This command will reload the systemd, making it aware of your new service file or any changes to existing files.

  1. To ensure your service starts automatically at boot, run the command:
sudo systemctl enable your_service.service

It enables your service to start at boot time.

ensuring that the service starts at boot
  1. To start your service immediately, execute the commmand:
sudo systemctl start your_service.service

It will start your service right away.

starting the service immediately
  1. Check the status of your service by typing the command:
sudo systemctl status your_service.service

This command checks and displays the current status of your service, confirming it’s active and running.

checking the status of the service
  1. If your service isn’t starting correctly, execute the command:
sudo journalctl -u your_service.service

This command displays the journal logs for your service, helping identify any errors or issues during its startup.

checking logs for any error

5 Common Errors to Avoid in Systemd Service Creation

Creating systemd services is a key skill for managing Linux systems efficiently. But it’s easy to trip up if you’re new. To guide you smoothly through the process, I am spotlighting five typical errors that can occur and offering practical advice to help you avoid these common pitfalls and enhance your system management:

  1. 📁 Incorrect File Placement: Placing the systemd unit file in the wrong directory can cause the system to not recognize or start the service. Always save unit files in /etc/systemd/system for system-wide services.
  2. 🔒 Permission Problems: If your script isn’t executable, systemd won’t be able to run it. Ensure script permissions are correctly set using chmod +x /path/to/your/script to make it executable.
  3. 🛠 Syntax Errors in Unit Files: Syntax mistakes in unit files can prevent services from starting. Validate your file with systemd-analyze verify yourservice.service to catch errors before they cause problems.
  4. 🔄 Service Dependency Conflicts: Incorrectly managed dependencies or ordering can cause services to fail at startup. Use the After= and Requires= directives carefully to define the correct startup sequence and dependencies.
  5. ⚙️ Neglecting Resource Limits: Omitting resource limits in your service unit can lead to excessive resource consumption. Utilize LimitNOFILE= and similar directives to control resource usage and prevent system strain.

Linux Create Systemd Service: Wrapping it Up

In this guide, I walked you through creating a systemd service in Linux, from writing the service file to managing and troubleshooting it. With these steps, you can confidently set up reliable background processes for your applications, ensuring smooth operations and quick recovery from issues.

For further learning, I recommend exploring:

Frequently Asked Questions

What is the difference between a systemd service and a traditional init script?

Systemd services provide more advanced features than traditional init scripts, like parallel startup and better dependency management. Systemd also offers more granular control over service execution and system resources, making it more efficient and flexible.

Is there a method to prioritize service startup orders in systemd?

Yes, the systemd allows you to prioritize service startup orders using the Before= and After= directives in unit files. By specifying these directives, you can control the sequence in which services start, ensuring dependencies are correctly managed and services start in the desired order.

Can I run a systemd service under a specific user and group?

Yes, you can run a systemd service under a specific user and group by using the User= and Group= directives in the service’s unit file. This approach enhances security by limiting the service’s permissions and access rights, reducing the potential impact of vulnerabilities.

How do I set up a systemd service to send email notifications on failure?

To set up a systemd service to send email notifications on failure, integrate the service with an external script or monitoring tool configured to send emails. Use the OnFailure= directive in the unit file to specify the action or script to execute when the service fails.

How can I automatically restart a systemd service after a specific time has elapsed?

You can automatically restart a systemd service after a specific time using the RuntimeMaxSec= directive, which defines a maximum runtime before the service is restarted. Alternatively, combining systemd timers with service units can schedule regular restarts, managing service states effectively.

Can systemd services depend on each other, and how is this managed?

Yes, systemd services can depend on each other, managed through directives like Requires=, Wants=, and After= in unit files. These directives define dependency relationships and startup order, ensuring services start only after their dependencies are satisfied for coherent system operation.

Ojash

Author

Ojash is a skilled Linux expert and tech writer with over a decade of experience. He has extensive knowledge of Linux's file system, command-line interface, and software installations. Ojash is also an expert in shell scripting and automation, with experience in Bash, Python, and Perl. He has published numerous articles on Linux in various online publications, making him a valuable resource for both seasoned Linux users and beginners. Ojash is also an active member of the Linux community and participates in Linux forums.

Akshat

Reviewer

Akshat is a software engineer, product designer and the co-founder of Scrutify. He's an experienced Linux professional and the senior editor of this blog. He is also an open-source contributor to many projects on Github and has written several technical guides on Linux. Apart from that, he’s also actively sharing his ideas and tutorials on Medium and Attirer. As the editor of this blog, Akshat brings his wealth of knowledge and experience to provide readers with valuable insights and advice on a wide range of Linux-related topics.

Share this article
Shareable URL
Prev Post

6 Proven Ways to Add Root Permissions to User Linux

Next Post

4 Simple Ways to Linux Switch Users

Leave a Reply

Your email address will not be published. Required fields are marked *

Read next