Mastering Linux services
The Linux powerhouse is behind countless servers and systems as we talked, it operates efficiently thanks to its services and background processes. But what is a service realy?
As you may know any operating systems requires some programs running under the hood (in the background) to works properly and managing these services is crucial for reals ninja developers 🥷🏼
A Linux service (or daemon 😈) is a script (or set of ascripts/pplications) that runs in the background. It listens continuously for incoming requests and sends a response based on the given request. A service is different from a process as a process is an application or a script that can be running in the foreground or the background. More on wikipedia Do not pay attention at the complicated schema we will get there 😇
Note
Linux service are managed using systemd
and systemctl
commands. This the dynamic duo that controls the Linux service landscape 🎶
You are probably wondering if you know some Linux services. Well, of course you know
httpd
,mysql
,bluetooth
... I think you've got the idea !
This article dives deep into managing Linux services, offering examples and insights to harness the full potential of systemctl
and systemd
and review some use cases in order to master Linux services like a real shinobi 🥷🏼
Understanding systemd
and Services
At the heart of modern Linux distributions lies systemd
, an init system and system manager that has become the de facto standard. It's responsible for initializing the system components and managing services throughout the system's lifecycle.
A service in Linux like we said is a program or a set of programs running in the background, waiting to be used and performing essential tasks (we can also defined dummy services do not worry 🤣).
These could range from web servers like Apache or Nginx to system-level services like logging (rsyslog
or journald
) and cron jobs, databases...
Available common services
Like Linux commands line, you do not need nt know them all (it is not like pokemon) like always the question is knowing how and where to search when you have the problem 🕵🏽
It is good to know for your culture some common used services, in no particular order:
- SSH - SSH Command - Usage, Options, Configuration
- Apache (web server) - The Apache HTTP Server Project
- Bind 9 (for DNS) - Internet Systems Consortium
- Sendmail, Qmail, or Zimbra for email. SENDMAIL INSTALLATION AND OPERATION GUIDE
- Samba (as a Windows Server) - opening windows to a wider world
- FTP with PureFTP - Pure-FTPd
- NFS or iSCSI for data storage or backup - Wikipedia + What Is iSCSI and How Does It Work?
- Bacula or something similar for network backup.The best free enterprise open source backup software for Linux
Here you can find the vast majority of available services for any Linus distribution list and explain in this article : A comprehensive list of available Linux services
The systemctl
command
systemctl
is the command line to control the systemd
system and service manager. It provides a suite of commands to manage systemd units, where a unit can be a service (.service), a mount point (.mount), a socket (.socket), and more.
For example, use it to list all unit files in your Linux server :
Terminal will list in the output unit files with the service type in a tabular format, including their state and vendor preset.
Service state is the systemd units’ operational status. The most common ones are:
- Enabled – active services running in the background.
- Disabled – disabled services that users can enable directly using the start command.
- Masked – stopped services that can only be started by removing the masked property.
- Static – services that only run when another program or unit requires them.
- Failed – inactive services that can’t load or operate properly.
Meanwhile, the vendor preset is a service’s default configuration, which determines whether it starts during the boot time or not. You can also use the systemctl list-units
command to list properly loaded services.
Note
Older Linux operating systems use a different service manager called System V. To manage services in this init system, use the service command.
For example, run the following to list all daemons:
service --status-all
Checking Service Status
To check the status of a service, including whether it's running and its recent log entries run this command :
You should see this kind of output it's mean your ssh services is well and you can connect your machine without problem 😎
● ssh.service - OpenBSD Secure Shell server
Loaded: loaded (/lib/systemd/system/ssh.service; enabled; vendor preset: enabled)
Active: active (running) since Wed 2024-02-21 13:05:25 CET; 1 week 0 days ago
Docs: man:sshd(8)
man:sshd_config(5)
Main PID: 1007 (sshd)
Tasks: 1 (limit: 38183)
Memory: 8.1M
CPU: 1.610s
CGroup: /system.slice/ssh.service
└─1007 "sshd: /usr/sbin/sshd -D [listener] 0 of 10-100 startups"
févr. 28 14:41:44 benjamin-rig-48 sshd[2426667]: pam_unix(sshd:session): session opened for user benjamin(uid=1000) by (uid=0)
Restarting and Reloading Services
On the same way you can also restart or reload a certain service with the restart
or reload
command :
or
It is very usefull when you are debeuging your computer or install some new linux plugins or hard configs, you may have to juggle with these commands 😇
Write your own start-up service
Knowing how to write systemd service files is crucial for several reasons: automation, deployment, scalability and many more. It's allow you to deploy and manage your applications more effectively, ensuring that they run reliably and efficiently as part of a system's startup and maintenance routines.
For this use case let's try to kick of a docker-compose containers stack when the machine is up. First edit this file :
Then write this in the file :
[Unit]
Description=Some docker-compose stack
Requires=docker.service
After=docker.service
[Service]
Type=oneshot
RemainAfterExit=yes
WorkingDirectory=/home/benjamin/workspace/cqueue
ExecStart=/usr/bin/docker-compose up -d --remove-orphans
ExecStop=/usr/bin/docker-compose down
User=benjamin
[Install]
WantedBy=multi-user.target
Let's break down each section and directive to understand its purpose and functionality:
[Unit] Section
Description
: Provides a human-readable description of the service, in this case, "Some docker-compose stack".Requires
: Specifies that this service depends on docker.service. This means that docker.service must be started before this service.After
: Ensures that this service starts after docker.service has been started. This is to ensure that Docker is fully operational before attempting to start the Docker Compose stack.
[Service] Section
Type=oneshot
: Indicates that this service is intended to run a single task and then remain inactive. oneshot is commonly used for scripts that perform a single job and then exit.RemainAfterExit=yes
: Even after the ExecStart command has finished, systemd considers the service as active. This is useful for services that don't run continuously but whose completion signifies that they're still 'active' or 'up'.WorkingDirectory
: Specifies the working directory for executing the ExecStart and ExecStop commands. Here, it's set to /home/benjamin/workspace/cqueue, which is likely where thedocker-compose.yml
file resides.ExecStart
: Defines the command to start the service. In this case, it uses docker-compose up -d --remove-orphans to start the Docker Compose stack in detached mode and remove any orphaned services.ExecStop
: Specifies the command to stop the service, which here is docker-compose down, shutting down the Docker Compose stack.User
: Defines the user under which the service commands (ExecStart and ExecStop) are executed. This ensures that the Docker Compose stack is run as the user benjamin, not as root or any other system user.
[Install] Section
WantedBy=multi-user.target
: Determines the target that this service should be attached to if enabled. multi-user.target is a standard target for systems that have multiple users and networking but don't necessarily have a graphical interface. Setting this makes the Docker Compose stack start automatically at boot under the conditions defined by themulti-user.target
.
This service file is a template for managing a Docker Compose project as a systemd service. It ensures that the Docker Compose stack starts after Docker itself is up and running, runs the commands as a specific user, and integrates the service into the system's startup process.
Tips
This setup is particularly useful for ensuring that multi-container Docker applications start automatically and cleanly on system boot, without manual intervention, making it highly useful for server environments or development workspaces that rely on Docker Compose managed applications.
Reload the systemd
configuration
To make the new service available we have to reload the systemd
configuration, noting fancy just type this command below in the same terminal :
Enable the service to start at boot time
Then you can finnaly start your service with the command:
Managing System State with systemctl
systemctl
isn't limited to managing services. It can also manage system states, referred to as "targets" in systemd
language.
Changing Runlevels/Targets
To change the system's runlevel/target (e.g., graphical user interface or multi-user command line):
systemctl
offer a powerful and flexible system for managing services and system states in Linux. Understanding how to leverage this tool can greatly enhance your ability to maintain, troubleshoot, and optimize Linux systems.
Whether you're a system administrator managing hundreds of servers or a developer looking to fine-tune your local development environment, mastering systemctl
commands is an invaluable skill in the Linux world 🚀
Tips
To create documentation, use the >
director to output the systemctl
command results in a file. For example, use the following command to create a file containing a service list:
sudo systemctl list-unit-files --type service --all > service_list.txt
Understand the Dependencies Between Services
Before you go turning off services willy-nilly, it's super important to get the lowdown on what depends on what. It's kinda like pulling a block out of a Jenga tower; you gotta know which ones are safe to pull so the whole thing doesn’t come crashing down.
Take your website running on PHP-FPM and Apache httpd, for example. Knock out Apache, and bam, PHP-FPM throws a fit, and your site’s down for the count. Since a bunch of services might be piggybacking off a single one, figuring out who messed up the party can be like finding a needle in a haystack. So, a little advice? Map out who needs who before you hit the off switch. It'll save you a headache later.
Keeping an eye on how your services are feeling and performing is pretty much like being the doctor of your server. Catching a cold (aka performance issues) early can stop it from turning into full-blown flu (aka downtime). Plus, it’s always handy to have the deets on what’s going on under the hood, especially when you're trying to figure out if that latest update is playing nice.
Wrap it up
So, here we are in the end. In summary, diving deep into Linux services and mastering tools like systemctl
will equip you with the ability to finely tune your application environment, ensure stability, and react swiftly to issues as they arise.
It's a good skill set to have that enhances your development practices, bolsters your troubleshooting toolkit, and deepens your understanding of the Linux operating system. Whether you're working on personal projects, enterprise applications, or anywhere in between, the knowledge of Linux services is a powerful asset in a developer's arsenal 🥷🏼