How to start and stop services with systemctl

How to Start and Stop Services with systemctl Table of Contents 1. [Introduction](#introduction) 2. [Prerequisites](#prerequisites) 3. [Understanding systemd and systemctl](#understanding-systemd-and-systemctl) 4. [Basic systemctl Commands](#basic-systemctl-commands) 5. [Starting Services](#starting-services) 6. [Stopping Services](#stopping-services) 7. [Restarting and Reloading Services](#restarting-and-reloading-services) 8. [Checking Service Status](#checking-service-status) 9. [Enabling and Disabling Services](#enabling-and-disabling-services) 10. [Advanced systemctl Operations](#advanced-systemctl-operations) 11. [Working with Service Files](#working-with-service-files) 12. [Common Use Cases and Examples](#common-use-cases-and-examples) 13. [Troubleshooting Common Issues](#troubleshooting-common-issues) 14. [Best Practices](#best-practices) 15. [Security Considerations](#security-considerations) 16. [Conclusion](#conclusion) Introduction The `systemctl` command is the primary tool for controlling systemd services on modern Linux distributions. Whether you're managing web servers, databases, or custom applications, understanding how to properly start, stop, and manage services is essential for system administration and DevOps operations. This comprehensive guide will teach you everything you need to know about using systemctl to manage services effectively. You'll learn the fundamental commands, explore advanced features, and discover best practices that will help you maintain robust and reliable Linux systems. By the end of this article, you'll be able to confidently manage any systemd service, troubleshoot common issues, and implement proper service management workflows in both development and production environments. Prerequisites Before diving into systemctl commands, ensure you have: - Linux System with systemd: Most modern distributions including Ubuntu 16.04+, CentOS 7+, Fedora, Debian 8+, and RHEL 7+ - Root or sudo privileges: Required for most service management operations - Basic terminal knowledge: Familiarity with command-line interface - Understanding of Linux services: Basic knowledge of what services are and their purpose To verify systemd is running on your system: ```bash systemctl --version ``` This command should return version information if systemd is properly installed and running. Understanding systemd and systemctl What is systemd? Systemd is a system and service manager that has become the standard init system for most Linux distributions. It replaces traditional SysV init scripts and provides: - Parallel service startup: Faster boot times through concurrent service initialization - Dependency management: Automatic handling of service dependencies - Process supervision: Monitoring and automatic restart of failed services - Resource management: Control over CPU, memory, and I/O resources - Logging integration: Centralized logging through journald What is systemctl? Systemctl is the command-line interface for controlling systemd. It allows you to: - Start, stop, restart, and reload services - Enable and disable services for automatic startup - Check service status and logs - Manage system targets (runlevels) - Control system power states Service Unit Files Services in systemd are defined by unit files with the `.service` extension. These files contain: - Service description and documentation - Dependencies and ordering requirements - Execution parameters and environment - Restart policies and failure handling Basic systemctl Commands Command Syntax The basic syntax for systemctl commands follows this pattern: ```bash systemctl [OPTIONS] COMMAND [SERVICE_NAME] ``` Essential Commands Overview | Command | Purpose | Example | |---------|---------|---------| | `start` | Start a service | `systemctl start nginx` | | `stop` | Stop a service | `systemctl stop nginx` | | `restart` | Restart a service | `systemctl restart nginx` | | `reload` | Reload service configuration | `systemctl reload nginx` | | `status` | Check service status | `systemctl status nginx` | | `enable` | Enable service at boot | `systemctl enable nginx` | | `disable` | Disable service at boot | `systemctl disable nginx` | Starting Services Basic Service Start To start a service, use the `start` command: ```bash sudo systemctl start service_name ``` Example: Starting Apache web server ```bash sudo systemctl start apache2 ``` Starting Multiple Services You can start multiple services simultaneously: ```bash sudo systemctl start nginx mysql redis-server ``` Verification After Starting Always verify that a service started successfully: ```bash systemctl is-active nginx ``` This returns `active` if the service is running, or `inactive` if it's not. Starting Services with Dependencies When you start a service, systemd automatically starts its dependencies. For example, starting a web application might automatically start the database it depends on. ```bash Starting a web application that depends on MySQL sudo systemctl start mywebapp MySQL will start automatically if it's a dependency ``` Stopping Services Basic Service Stop To stop a running service: ```bash sudo systemctl stop service_name ``` Example: Stopping Nginx ```bash sudo systemctl stop nginx ``` Graceful vs Forceful Stopping By default, `systemctl stop` sends a SIGTERM signal for graceful shutdown. If the service doesn't respond within the timeout period, systemd sends SIGKILL. Stopping Multiple Services Stop multiple services at once: ```bash sudo systemctl stop apache2 mysql redis-server ``` Emergency Service Termination For immediate termination without graceful shutdown: ```bash sudo systemctl kill service_name ``` Example with specific signal: ```bash sudo systemctl kill -s SIGKILL nginx ``` Restarting and Reloading Services Restart vs Reload - Restart: Completely stops and starts the service - Reload: Reloads configuration without stopping the service Restarting Services ```bash sudo systemctl restart service_name ``` Example: Restarting SSH daemon ```bash sudo systemctl restart sshd ``` Reloading Service Configuration When you modify configuration files, reload instead of restart when possible: ```bash sudo systemctl reload nginx ``` Try-Reload-or-Restart This command attempts to reload, but restarts if reload isn't supported: ```bash sudo systemctl reload-or-restart nginx ``` Conditional Restart Restart only if the service is already running: ```bash sudo systemctl condrestart service_name ``` Checking Service Status Basic Status Check ```bash systemctl status service_name ``` Example output for Nginx: ``` ● nginx.service - A high performance web server and a reverse proxy server Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled) Active: active (running) since Mon 2024-01-15 10:30:45 UTC; 2h 15min ago Docs: man:nginx(8) Process: 1234 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=0/SUCCESS) Process: 1235 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code=exited, status=0/SUCCESS) Main PID: 1236 (nginx) Tasks: 5 (limit: 4915) Memory: 6.2M CGroup: /system.slice/nginx.service ├─1236 nginx: master process /usr/sbin/nginx -g daemon on; master_process on; └─1237 nginx: worker process ``` Quick Status Checks Check if a service is active: ```bash systemctl is-active nginx ``` Check if a service is enabled: ```bash systemctl is-enabled nginx ``` Check if a service failed: ```bash systemctl is-failed nginx ``` Listing All Services List all loaded services: ```bash systemctl list-units --type=service ``` List all available services (loaded and not loaded): ```bash systemctl list-unit-files --type=service ``` Filter by state: ```bash systemctl list-units --type=service --state=running systemctl list-units --type=service --state=failed ``` Enabling and Disabling Services Understanding Enable vs Start - Enable: Configure service to start automatically at boot - Start: Start the service immediately Enabling Services Enable a service for automatic startup: ```bash sudo systemctl enable service_name ``` Enable and start simultaneously: ```bash sudo systemctl enable --now service_name ``` Disabling Services Disable automatic startup: ```bash sudo systemctl disable service_name ``` Disable and stop simultaneously: ```bash sudo systemctl disable --now service_name ``` Masking Services Prevent a service from being started manually or automatically: ```bash sudo systemctl mask service_name ``` Unmask a service: ```bash sudo systemctl unmask service_name ``` Advanced systemctl Operations Working with Targets Targets are groups of services that represent system states (similar to runlevels): ```bash Switch to multi-user target (text mode) sudo systemctl isolate multi-user.target Switch to graphical target (GUI mode) sudo systemctl isolate graphical.target Set default target sudo systemctl set-default multi-user.target ``` Service Dependencies View service dependencies: ```bash systemctl list-dependencies nginx ``` Show reverse dependencies (what depends on this service): ```bash systemctl list-dependencies nginx --reverse ``` System Power Management ```bash Reboot system sudo systemctl reboot Shutdown system sudo systemctl poweroff Suspend system sudo systemctl suspend Hibernate system sudo systemctl hibernate ``` Analyzing Boot Performance ```bash Show boot time systemd-analyze Show service startup times systemd-analyze blame Show critical chain systemd-analyze critical-chain ``` Working with Service Files Locating Service Files Service files are typically located in: - `/lib/systemd/system/` - System-provided services - `/etc/systemd/system/` - Administrator-created services - `/usr/lib/systemd/system/` - Package-installed services Viewing Service Files ```bash systemctl cat nginx ``` Editing Service Files Use the built-in editor: ```bash sudo systemctl edit nginx ``` This creates an override file in `/etc/systemd/system/nginx.service.d/override.conf`. For full service file editing: ```bash sudo systemctl edit --full nginx ``` Reloading systemd Configuration After modifying service files: ```bash sudo systemctl daemon-reload ``` Creating Custom Service Files Example custom service file (`/etc/systemd/system/myapp.service`): ```ini [Unit] Description=My Application After=network.target [Service] Type=simple User=myuser WorkingDirectory=/opt/myapp ExecStart=/opt/myapp/bin/myapp Restart=always RestartSec=10 [Install] WantedBy=multi-user.target ``` Common Use Cases and Examples Web Server Management Managing Nginx: ```bash Start Nginx sudo systemctl start nginx Check status systemctl status nginx Enable for boot sudo systemctl enable nginx Reload configuration after changes sudo systemctl reload nginx View logs journalctl -u nginx -f ``` Database Server Management Managing MySQL: ```bash Start MySQL sudo systemctl start mysql Check if MySQL is running systemctl is-active mysql Enable automatic startup sudo systemctl enable mysql Restart after configuration changes sudo systemctl restart mysql ``` SSH Service Management Managing SSH daemon: ```bash Check SSH status systemctl status sshd Restart SSH (be careful with remote connections!) sudo systemctl restart sshd Reload SSH configuration sudo systemctl reload sshd ``` Custom Application Management Managing a Node.js application: ```bash Create service file sudo nano /etc/systemd/system/nodeapp.service Reload systemd sudo systemctl daemon-reload Enable and start sudo systemctl enable --now nodeapp Monitor logs journalctl -u nodeapp -f ``` Container Runtime Management Managing Docker: ```bash Start Docker daemon sudo systemctl start docker Enable Docker at boot sudo systemctl enable docker Check Docker status systemctl status docker Restart Docker sudo systemctl restart docker ``` Troubleshooting Common Issues Service Won't Start Check service status and logs: ```bash systemctl status service_name journalctl -u service_name -n 50 ``` Common causes: - Configuration file errors - Missing dependencies - Permission issues - Port conflicts Service Fails to Stop Force stop a service: ```bash sudo systemctl kill service_name ``` Check for remaining processes: ```bash ps aux | grep service_name ``` Service Starts But Immediately Fails Check the journal for detailed logs: ```bash journalctl -u service_name --since "1 hour ago" ``` Verify service file syntax: ```bash systemd-analyze verify /path/to/service.service ``` Permission Denied Errors Ensure proper sudo usage: ```bash sudo systemctl start service_name ``` Check user permissions: ```bash groups $USER ``` Dependency Issues Check service dependencies: ```bash systemctl list-dependencies service_name ``` Start dependencies manually: ```bash sudo systemctl start dependency_service sudo systemctl start main_service ``` Configuration Not Loading Reload systemd daemon: ```bash sudo systemctl daemon-reload ``` Restart the service: ```bash sudo systemctl restart service_name ``` Boot-time Service Failures Check failed services: ```bash systemctl --failed ``` Analyze boot process: ```bash systemd-analyze critical-chain ``` Best Practices Service Management Workflow 1. Always check status before making changes: ```bash systemctl status service_name ``` 2. Test configuration before applying: ```bash nginx -t # For Nginx apache2ctl configtest # For Apache ``` 3. Use reload instead of restart when possible: ```bash sudo systemctl reload service_name ``` 4. Monitor logs during changes: ```bash journalctl -u service_name -f ``` Automation and Scripting Create service management scripts: ```bash #!/bin/bash restart-web-stack.sh echo "Restarting web stack..." sudo systemctl restart mysql sudo systemctl restart nginx sudo systemctl restart php7.4-fpm echo "Checking services..." systemctl is-active mysql nginx php7.4-fpm ``` Documentation and Change Management 1. Document service dependencies 2. Keep configuration backups 3. Test changes in staging first 4. Maintain service restart procedures Monitoring and Alerting Set up service monitoring: ```bash Check if critical services are running for service in nginx mysql sshd; do if ! systemctl is-active --quiet $service; then echo "WARNING: $service is not running!" fi done ``` Resource Management Monitor service resource usage: ```bash systemctl show service_name --property=MemoryCurrent systemctl show service_name --property=CPUUsageNSec ``` Security Considerations Principle of Least Privilege - Run services with minimal required permissions - Use dedicated service users - Avoid running services as root when possible Service Hardening Example hardened service file: ```ini [Unit] Description=Secure Web Application After=network.target [Service] Type=simple User=webapp Group=webapp WorkingDirectory=/opt/webapp ExecStart=/opt/webapp/bin/app Security settings NoNewPrivileges=true PrivateTmp=true ProtectSystem=strict ProtectHome=true ReadWritePaths=/var/log/webapp [Install] WantedBy=multi-user.target ``` Access Control - Limit who can manage services - Use sudo rules for specific service operations - Monitor service management activities Network Security - Configure firewalls before starting network services - Use service-specific network namespaces when possible - Regularly audit listening ports Conclusion Mastering systemctl is essential for effective Linux system administration. This comprehensive guide has covered everything from basic service start and stop operations to advanced troubleshooting and security considerations. Key Takeaways 1. systemctl is the primary interface for managing systemd services on modern Linux systems 2. Always verify service status after making changes 3. Use reload instead of restart when configuration changes don't require a full restart 4. Monitor logs actively during service operations 5. Follow security best practices when configuring services 6. Understand dependencies to avoid service conflicts 7. Document your procedures for consistent operations Next Steps To continue improving your systemd and systemctl skills: 1. Practice with different services in a test environment 2. Learn about systemd timers for scheduled tasks 3. Explore systemd-analyze for performance optimization 4. Study service file creation for custom applications 5. Implement monitoring solutions for production environments 6. Investigate systemd security features like sandboxing and resource limits Additional Resources - systemd documentation: Official systemd manual pages - journalctl: Learn advanced log analysis techniques - systemd unit file specification: Detailed service file configuration - systemd security: Hardening and sandboxing features With the knowledge gained from this guide, you're well-equipped to manage services effectively and maintain robust Linux systems. Remember to always test changes in non-production environments first, and keep learning about new systemd features and best practices as they evolve. Whether you're managing a single server or a large infrastructure, these systemctl skills will serve as the foundation for reliable service management and system administration success.