Service Management (systemctl, service)
Category: Intermediate Linux Commands
Type: Linux Commands
Generated on: 2025-07-10 03:09:49
For: System Administration, Development & Technical Interviews
Service Management Cheatsheet (systemctl, service)
Section titled “Service Management Cheatsheet (systemctl, service)”This cheatsheet provides a comprehensive guide to managing system services using systemctl and service commands in Linux. It covers basic syntax, practical examples, common options, advanced usage, troubleshooting, and related commands. It’s designed for both beginners and experienced system administrators and developers.
1. Command Overview
systemctl: The primary command for managing systemd services. systemd is the system and service manager for most modern Linux distributions. It provides a unified interface for controlling and monitoring system processes. It’s the preferred tool for modern Linux systems.service: A legacy command for managing services. It acts as a wrapper around init scripts (e.g., SysVinit). While still functional on many systems,systemctlis generally preferred due to its wider range of features and integration with systemd. Useserviceprimarily for legacy systems or when dealing with services that haven’t been fully migrated to systemd.
When to Use:
systemctl:- Starting, stopping, restarting, and reloading services.
- Checking the status of services.
- Enabling or disabling services to start on boot.
- Managing service dependencies.
- Viewing service logs.
service:- Starting, stopping, restarting services on systems using SysVinit or where systemd is not fully integrated.
- Checking the status of services on older systems.
- When interacting with legacy init scripts directly.
2. Basic Syntax
systemctl
systemctl [OPTIONS...] COMMAND [NAME...]OPTIONS: Flags that modify the behavior of the command.COMMAND: The action to perform on the service (e.g.,start,stop,status).NAME: The name of the service (e.g.,nginx.service,apache2.service). If the.serviceextension is omitted, systemctl will usually assume it.
service
service NAME COMMAND [OPTIONS...]NAME: The name of the service (e.g.,nginx,apache2).COMMAND: The action to perform (e.g.,start,stop,restart,status).OPTIONS: Service-specific options (rarely used).
3. Practical Examples
systemctl
-
Start a service:
Terminal window sudo systemctl start nginxExpected Output (no output on success, or an error message if it fails):
# (No output if successful) -
Stop a service:
Terminal window sudo systemctl stop nginxExpected Output (no output on success, or an error message if it fails):
# (No output if successful) -
Restart a service:
Terminal window sudo systemctl restart nginxExpected Output (no output on success, or an error message if it fails):
# (No output if successful) -
Reload a service (without downtime): This is useful for applying configuration changes.
Terminal window sudo systemctl reload nginxExpected Output (no output on success, or an error message if it fails):
# (No output if successful) -
Check the status of a service:
Terminal window systemctl status nginxExpected Output:
● nginx.service - A high performance web server and a reverse proxy serverLoaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)Active: active (running) since Mon 2023-10-23 10:00:00 UTC; 1h agoDocs: man:nginx(8)Main PID: 1234 (nginx)Tasks: 2 (limit: 2288)Memory: 4.2MCPU: 20msCGroup: /system.slice/nginx.service└─1234 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;Oct 23 10:00:00 myhost systemd[1]: Started A high performance web server and a reverse proxy server. -
Enable a service to start on boot:
Terminal window sudo systemctl enable nginxExpected Output:
Created symlink /etc/systemd/system/multi-user.target.wants/nginx.service → /lib/systemd/system/nginx.service. -
Disable a service from starting on boot:
Terminal window sudo systemctl disable nginxExpected Output:
Removed /etc/systemd/system/multi-user.target.wants/nginx.service. -
Check if a service is enabled to start on boot:
Terminal window systemctl is-enabled nginxPossible Outputs:
enabled,disabled,static,indirect.
service
-
Start a service:
Terminal window sudo service nginx startExpected Output (may vary depending on the init script):
[ ok ] Starting nginx (via systemctl): nginx.service. -
Stop a service:
Terminal window sudo service nginx stopExpected Output (may vary depending on the init script):
[ ok ] Stopping nginx (via systemctl): nginx.service. -
Restart a service:
Terminal window sudo service nginx restartExpected Output (may vary depending on the init script):
[ ok ] Restarting nginx (via systemctl): nginx.service. -
Check the status of a service:
Terminal window sudo service nginx statusExpected Output (may vary depending on the init script):
[ ok ] nginx is running.
4. Common Options
systemctl
-q,--quiet: Suppress output (useful for scripting).-n,--lines=NUMBER: Show only the last NUMBER lines of the journal log. Useful withsystemctl status.--user: Operate on user services (services specific to a user session). Requires the user to be logged in.--system: Operate on system services (the default).--no-ask-password: Do not prompt for passwords (useful for automated scripts). Requires appropriate permissions.-t,--type=TYPE: Filter services by type (e.g.,service,socket,mount,device).--all: Show all units, even those that are not active.--failed: List only failed units.
service
- The
servicecommand has very limited options. Specific options are usually passed to the init script itself, which varies from service to service. Refer to the init script’s documentation for available options.
5. Advanced Usage
systemctl
-
Masking a service: Prevents a service from being started, even if it’s enabled.
Terminal window sudo systemctl mask nginxThis creates a symlink to
/dev/null, effectively disabling the service.To unmask:
Terminal window sudo systemctl unmask nginx -
List all running services:
Terminal window systemctl list-units --type=service --state=running -
List all failed services:
Terminal window systemctl --failed -
Show dependencies of a service:
Terminal window systemctl list-dependencies nginx -
View the journal logs for a service:
Terminal window journalctl -u nginxTo view logs in real-time:
Terminal window journalctl -fu nginx -
Edit a service file: Allows you to customize the service configuration.
Terminal window sudo systemctl edit nginxThis creates an override file in
/etc/systemd/system/nginx.service.d/override.conf. Changes in this file will override the original service file. -
Reload systemd configuration: After making changes to service files, you need to reload the systemd configuration.
Terminal window sudo systemctl daemon-reload -
Isolate a target: Stop all units except those required by the specified target. Useful for debugging and recovery. For example, to isolate the rescue target:
Terminal window sudo systemctl isolate rescue.targetWARNING: This can disrupt running services. Use with caution. To return to the normal multi-user target:
Terminal window sudo systemctl isolate multi-user.target -
Checking Systemd Boot Time:
Terminal window systemd-analyze timeTerminal window systemd-analyze blame # lists services by the amount of time they took to start.
service
-
The advanced usage of
serviceis limited and heavily dependent on the specific init script. You might need to examine the init script itself (usually located in/etc/init.d/) to understand its capabilities. For example:Terminal window sudo /etc/init.d/nginx helpThis might display available options for the
nginxinit script.
6. Tips & Tricks
- Tab completion: Use tab completion to quickly find service names. Type
systemctl start ng<TAB>to auto-completenginxif it’s the only matching service. - Wildcards: You can use wildcards to manage multiple services at once. For example,
systemctl stop myapp-*will stop all services starting withmyapp-. - Service aliases: Some services have aliases. For example,
mysqlmight be an alias formariadb. Usesystemctl status mysqlto see the actual service name. - Check return codes in scripts: Use
$?to check the return code of a command in a script. A return code of 0 indicates success, while a non-zero return code indicates an error. - Chaining commands: You can chain commands using
&&to execute them sequentially only if the previous command was successful. For example:sudo systemctl stop nginx && sudo systemctl start nginx. - Using
systemctl show: Usesystemctl show <service>to view all properties of a service, including its dependencies, status, and configuration details. This is useful for debugging and understanding service behavior.
7. Troubleshooting
- Service fails to start:
- Check the service status:
systemctl status <service> - View the journal logs:
journalctl -u <service> - Check the service configuration file for errors. Use
systemctl cat <service>to view the contents of the service file. - Verify that all dependencies are met.
- Check file permissions.
- Check the service status:
- Service fails to stop:
- Check if the service is hung or unresponsive.
- Try killing the process manually:
sudo kill <PID>(get the PID fromsystemctl status). - If the service is still unresponsive, try a forceful kill:
sudo kill -9 <PID>. WARNING: This can lead to data corruption. Use as a last resort.
- Service fails to enable:
- Check if the service file exists in the correct location (
/lib/systemd/system/or/etc/systemd/system/). - Verify that the service file is properly formatted.
- Make sure there are no conflicting service files.
- Check if the service file exists in the correct location (
Failed to connect to bus: No such file or directory: This usually indicates that systemd is not running or that you’re trying to runsystemctlas a user without proper permissions. Try running the command withsudo. If that doesn’t work, ensure systemd is running:ps -ef | grep systemd.- “Unit not found.”: Double-check the spelling of the service name. Use tab completion to help avoid typos. Also, ensure that the service’s
.servicefile exists in the correct location. - Changes to service file not taking effect: Always run
sudo systemctl daemon-reloadafter modifying any service file. Then, restart the service for the changes to be applied.
8. Related Commands
journalctl: View system logs.systemd-analyze: Analyze system startup performance.ps: List running processes.kill: Terminate processes.init: The first process started by the kernel. systemd replaces traditionalinitsystems.update-rc.d(Debian-based systems): A legacy command for managing SysVinit scripts. Usesystemctlinstead where possible.chkconfig(Red Hat-based systems): A legacy command for managing SysVinit scripts. Usesystemctlinstead where possible.systemctl cat <service>: Displays the full service unit file contents, including any overridden parameters. Very useful for understanding the complete configuration.loginctl: Manage user sessions and systemd user instances. Useful for managing services that are specific to user sessions.
This cheatsheet provides a solid foundation for managing services in Linux. Remember to consult the official documentation for more detailed information and advanced usage scenarios. Always exercise caution when modifying system services, especially in production environments. Test changes in a development or staging environment before applying them to production.