Whether you are hosting a web application, setting up a custom backup script, or running a background monitor, knowing how to create Linux service files is a fundamental skill for any Linux administrator or developer.
In this guide, we will explore how Linux handles background processes, understand the modern service management architecture, and walk through the exact steps to create linux service units, manage them, and debug your own custom background applications.
- 1. Introduction: What is a Linux Service (Daemon)?
- 2. The Evolution of Linux Init Systems
- 3. What is systemd?
- 4. Service Configurations: Structure of a Unit File
- 5. Types of System Services (Unit Types)
- 6. Understanding Dependencies and Boot Order
- 7. Step-by-Step: How to Create Linux Service Files
- 8. Safely Modifying Services (systemctl edit)
- 9. Troubleshooting and Debugging Linux Services
- 10. The Ultimate Service Management Overview (systemctl)
1. Introduction: What is a Linux Service (Daemon)?
In the Linux and Unix world, a service (often called a daemon) is a program that runs continuously in the background. Unlike applications that require user interaction, daemons start automatically when the system boots up, run silently without an attached terminal, and wait for specific events or requests.
Common examples include web servers (nginx, apache2), database servers (mysql, postgresql), and remote access tools (sshd). Daemons typically end with the letter “d” to signify their background nature.
2. The Evolution of Linux Init Systems
To understand how to create linux service configurations today, it helps to understand how Linux manages them. The very first process started by the Linux kernel upon booting is the init system (always assigned Process ID 1). This system is responsible for starting every other service.
Historically, Linux used SysVinit (System V init). Administrators had to write complex, lengthy Bash shell scripts placed in /etc/init.d/ and manage “runlevels” to dictate boot order.
While some lightweight distributions still use older or alternative systems, the vast majority of modern Linux distributions (including Ubuntu, Debian, RHEL, CentOS, and Fedora) have standardized on a much more powerful and unified system called systemd.
3. What is systemd?
Systemd is a suite of basic building blocks for a Linux system, acting primarily as an initialization system and service manager. It was designed to overcome the limitations of SysVinit by offering:
- Parallelization: It can start multiple services at the same time, significantly reducing boot times.
- On-demand starting: It can defer starting a service until a specific socket or hardware is accessed.
- Dependency management: It strictly understands which services rely on others.
- Process tracking: It uses Linux control groups (cgroups) to track processes, meaning a service can’t escape being stopped by “forking” itself twice.
Because systemd is the modern standard, when you create linux service instances today, it means writing a systemd unit file.
4. Service Configurations: Structure of a Unit File
In the systemd environment, a configuration file that defines a service is called a unit file. These files are declarative—meaning you simply state what you want the service to do, rather than writing a complex script telling it how to do it.
A standard unit file is divided into three main sections:
[Unit]: Contains metadata and dependencies. It describes what the unit is, its documentation, and its relationship to other units (e.g., start this after the network is up).[Service]: Contains the specific configuration for the service itself. This includes the command to execute, the user to run as, and how to handle restarts if the service crashes.[Install]: Dictates behavior when the unit is enabled or disabled. It tells systemd which “target” (system state) should trigger this service to start on boot.
5. Types of System Services (Unit Types)
While we usually focus on .service files, systemd manages various types of resources, all referred to as “units.” Some common unit types include:
.service: A standard system service (a background process)..socket: Used for socket-based activation. systemd listens on a port and starts the associated.serviceonly when traffic arrives..timer: A systemd timer that acts like a cron job, triggering a service at specific times or intervals..target: A logical grouping of units, used to represent a system state (e.g.,multi-user.targetis the equivalent of a fully booted system without a GUI)..mount: Controls mounting directories in the file system.
6. Understanding Dependencies and Boot Order
One of systemd’s greatest strengths is how it handles boot order. You configure this in the [Unit] section using specific directives:
Requires=: A hard dependency. If your service Requires Service B, and Service B fails or stops, your service will also be stopped.Wants=: A soft dependency. If your service Wants Service B, systemd will try to start Service B. However, if Service B fails, your service will still continue to run. (This is generally preferred overRequires=).After=/Before=: These dictate order, not dependencies. If you useAfter=network.target, systemd guarantees the network target is reached before it attempts to start your service.
Linux Basics for Hackers
Always wanted to learn Linux but had no idea where to start? You’re in the right place! In this series, we’re going from zero to hero. I’ll be your guide as we ditch the “newbie” tag and turn you into a Linux pro. Let’s get started!
7. Step-by-Step: How to Create Linux Service Files
Let’s walk through a practical example to create linux service setups from scratch. Suppose you have a Python script located at /opt/myapp/app.py that you want to run as a background service.
Step 1: Write the Application/Script
Ensure your script is executable and works perfectly when run manually from the command line.
chmod +x /opt/myapp/app.py
Step 2: Create the Unit File
Custom unit files created by the system administrator should always be placed in /etc/systemd/system/. Create a file named myapp.service:
sudo nano /etc/systemd/system/myapp.service
Add the following configuration:
[Unit]
Description=My Custom Python Application
After=network.target
[Service]
# The user and group to run the service as (for security)
User=myuser
Group=myuser
# The directory to run the command from
WorkingDirectory=/opt/myapp
# The exact command to start your application
ExecStart=/usr/bin/python3 /opt/myapp/app.py
# Automatically restart the service if it crashes
Restart=on-failure
# Wait 5 seconds before restarting
RestartSec=5
[Install]
# Tells systemd to start this on regular boot
WantedBy=multi-user.target
Step 3: Reload the Daemon
Because you created a new file, you must tell systemd to scan the directory and load your new configuration:
sudo systemctl daemon-reload
Step 4: Start and Enable the Service
Now, start the service immediately:
sudo systemctl start myapp
To ensure the service starts automatically every time the server boots, enable it:
sudo systemctl enable myapp
8. Safely Modifying Services (systemctl edit)
Often, you will need to tweak a service provided by a package manager (like nginx or docker). These default unit files are stored in /lib/systemd/system/. Never edit files in /lib/systemd/system/ directly, as your changes will be overwritten the next time the software updates!
Instead, use the systemctl edit command:
sudo systemctl edit nginx
This opens a blank text editor. Any directives you add here will be saved as a “drop-in” snippet in /etc/systemd/system/nginx.service.d/override.conf. These settings will safely override or append to the vendor’s default configuration without modifying the original file.
9. Troubleshooting and Debugging Linux Services
If your service refuses to start or acts unexpectedly, Linux provides excellent built-in tools for debugging.
Check the Status First: The most common first step is checking the current status and the last few log lines:
sudo systemctl status myapp
Dive into the Logs with journalctl: Systemd captures all standard output (stdout) and standard error (stderr) from your service using its logging daemon, journald. You can read these logs using journalctl:
- View all logs for a specific service:
sudo journalctl -u myapp.service - View the last 50 lines and follow the logs in real-time (like
tail -f):sudo journalctl -u myapp.service -n 50 -f - View logs for this service only from the current boot session:
sudo journalctl -u myapp.service -b
10. The Ultimate Service Management Overview (systemctl)
The systemctl command is your primary tool for interacting with the service manager. Here is an overview of the most critical commands.
10.1 Viewing System Information
systemctl list-units --type=service: Lists all currently active services on the system.systemctl list-unit-files: Lists all available service files and whether they are enabled to start on boot or disabled.systemctl status <service>: Shows whether a service is running, its process ID (PID), memory usage, and recent log outputs.
10.2 Managing Services
systemctl start <service>: Starts a stopped service immediately.systemctl stop <service>: Stops a running service immediately.systemctl restart <service>: Stops and then immediately starts a service.systemctl reload <service>: Asks a running service to reload its configuration files gracefully without dropping active connections (supported by services like Nginx).systemctl enable <service>: Configures the service to start automatically on system boot.systemctl disable <service>: Prevents the service from starting automatically on boot.
10.3 Managing System States (Targets/Runlevels)
systemctl get-default: Shows the default system state on boot (e.g.,graphical.targetfor desktop,multi-user.targetfor a headless server).systemctl isolate graphical.target: Immediately switches the system state. (e.g., starting up the GUI on a server).systemctl rescue: Drops the system into a minimal, single-user mode for emergency repairs.
By understanding these core concepts and commands, you can confidently create linux service deployments, manage environments, and debug custom applications across modern Linux architectures.
