Linux Services & Daemons: The Complete Service Management Guide
Master service management, create custom services, and understand systemd like a professional system administrator.
📅 Published: Feb 2026
⏱️ Estimated Reading Time: 18 minutes
🏷️ Tags: systemd, systemctl, Services, Daemons, Linux Administration, DevOps
🎭 Understanding Services & Daemons
What are Services and Daemons?
Think of services as background workers in your Linux system. They're programs that run continuously, waiting to perform tasks when needed. The term daemon (pronounced "dee-mon") is the traditional Unix name for these background services.
Real-world analogy:
Web server (nginx/apache) = A receptionist always waiting to greet visitors
Database (mysql/postgres) = A librarian always ready to fetch books
SSH server = A security guard always checking IDs
Cron scheduler = An alarm clock that rings at specific times
Types of Services
System Services - Run at boot, essential for system operation
Network Services - Handle network connections (SSH, HTTP, etc.)
User Services - Started when user logs in
Socket-activated Services - Only start when connection arrives (efficient!)
The Evolution: From SysV init to systemd
Old way (SysV init): Each service had its own script in /etc/init.d/
sudo /etc/init.d/nginx start sudo service nginx restart
Modern way (systemd): All services managed by systemctl
sudo systemctl start nginx sudo systemctl restart nginx
Why systemd won: Faster boot times, better dependency management, consistent logging, and more features.
⚙️ Managing Services with systemd (systemctl)
systemctl: The Control Panel for Services
systemctl is your remote control for all services. Think of it like a universal TV remote that can control every device in your house.
Basic Service Operations
# Check if systemd is running ps -p 1 # If it shows "systemd", you're using systemd # View system status sudo systemctl status # List all units (services, mounts, sockets, etc.) sudo systemctl list-units # List only service units sudo systemctl list-units --type=service # List all unit files (enabled and disabled) sudo systemctl list-unit-files
Starting and Stopping Services
# Start a service sudo systemctl start nginx # Stop a service sudo systemctl stop nginx # Restart a service (stop then start) sudo systemctl restart nginx # Reload a service (re-read configuration without full restart) sudo systemctl reload nginx # Try to restart, if that fails, reload sudo systemctl try-restart nginx # Send a specific signal to a service sudo systemctl kill -s HUP nginx # Send HUP signal
Enabling and Disabling Services
# Enable a service to start at boot sudo systemctl enable nginx # Disable a service from starting at boot sudo systemctl disable nginx # Check if a service is enabled systemctl is-enabled nginx # Mask a service (prevent starting, even manually) sudo systemctl mask nginx # Useful for conflicting services # Unmask a service sudo systemctl unmask nginx # Enable and start in one command sudo systemctl enable --now nginx
Checking Service Status
# Basic status sudo systemctl status nginx # Status with all details sudo systemctl status nginx --full # Check if service is running sudo systemctl is-active nginx # Check if service failed sudo systemctl is-failed nginx # Show service properties sudo systemctl show nginx # Show specific property sudo systemctl show nginx -p MainPID sudo systemctl show nginx -p ExecStart
Viewing Service Logs
# View logs for a service sudo journalctl -u nginx # Follow logs in real-time (like tail -f) sudo journalctl -u nginx -f # View logs since boot sudo journalctl -u nginx -b # View logs from specific time sudo journalctl -u nginx --since "2024-02-10 09:00:00" sudo journalctl -u nginx --since "1 hour ago" # View logs with priority filter sudo journalctl -u nginx -p err # Only errors sudo journalctl -u nginx -p info # Only info messages # Show full log entries (not truncated) sudo journalctl -u nginx -o verbose
Advanced Service Management
# List dependencies of a service sudo systemctl list-dependencies nginx # List what depends on a service sudo systemctl list-dependencies nginx --reverse # Reload systemd configuration (after adding new unit files) sudo systemctl daemon-reload # Reset failed state of a service sudo systemctl reset-failed nginx # Show service startup time systemd-analyze blame | grep nginx # Check service security sudo systemd-analyze security nginx.service
Service States Explained
# Common service states: # active (running) - Service is running # active (exited) - Service completed its task # active (waiting) - Service running but waiting for something # inactive (dead) - Service not running # activating - Service is starting # deactivating - Service is stopping # failed - Service failed to start/run
Handling Failed Services
# List failed services sudo systemctl --failed # View why a service failed sudo systemctl status nginx sudo journalctl -u nginx -p err # Common troubleshooting steps: # 1. Check logs: sudo journalctl -u servicename # 2. Test configuration: sudo nginx -t (for nginx) # 3. Check dependencies: sudo systemctl list-dependencies servicename # 4. Check permissions and paths # 5. Manual start test: sudo /usr/sbin/nginx (run binary directly) # Restart after fixing issues sudo systemctl daemon-reload # If you changed unit file sudo systemctl restart nginx
📄 Understanding Unit Files
What are Unit Files?
Unit files are configuration files that tell systemd how to manage a service. Think of them as instruction manuals for each service.
Unit File Locations
# System unit files (packages, administrators) /usr/lib/systemd/system/ # Default location (from packages) /etc/systemd/system/ # Local administrator overrides # User unit files (per-user services) ~/.config/systemd/user/ # User configuration /etc/systemd/user/ # Global user configuration # Check where a unit file is located sudo systemctl show nginx -p FragmentPath
Unit File Types
# Different types of units: .service # Service units (most common) .socket # Socket units (socket activation) .device # Device units .mount # Mount units .automount # Automount units .swap # Swap units .target # Target units (groups of units) .path # Path units (file/directory activation) .timer # Timer units (like cron jobs)
Anatomy of a Service Unit File
Let's examine a real unit file:
# View nginx service unit file cat /lib/systemd/system/nginx.service
Example nginx.service:
[Unit] Description=nginx - high performance web server Documentation=https://nginx.org/en/docs/ After=network-online.target remote-fs.target nss-lookup.target Wants=network-online.target [Service] Type=forking PIDFile=/run/nginx.pid ExecStartPre=/usr/sbin/nginx -t ExecStart=/usr/sbin/nginx ExecReload=/bin/kill -s HUP $MAINPID ExecStop=/bin/kill -s TERM $MAINPID PrivateTmp=true [Install] WantedBy=multi-user.target
Understanding Sections
[Unit] Section - Metadata and Dependencies
[Unit] Description=A descriptive name for your service Documentation=man:nginx(8) https://nginx.org/en/docs/ Requires=other.service # Hard dependency (stops if this stops) Wants=other.service # Soft dependency After=network.target # Start after these Before=some.service # Start before these Conflicts=conflicting.service # Cannot run together
[Service] Section - How to Run the Service
[Service] Type=simple # Most common type # Type=simple # systemd considers service started immediately # Type=forking # Service forks a child process (traditional daemons) # Type=oneshot # Run once and exit # Type=notify # Service notifies systemd when ready # Type=idle # Wait until all jobs finished ExecStart=/usr/bin/myapp # Command to start service ExecStartPre=/bin/setup.sh # Run before ExecStart ExecStartPost=/bin/notify.sh # Run after ExecStart ExecReload=/bin/reload.sh # Command for reload ExecStop=/bin/cleanup.sh # Command for stop Restart=on-failure # Auto-restart policy # Restart=no # Never restart # Restart=on-success # Restart on clean exit # Restart=on-failure # Restart on failure (default for many) # Restart=always # Always restart # Restart=on-abort # Restart on abort signal User=myuser # Run as specific user Group=mygroup # Run as specific group WorkingDirectory=/var/lib/myapp # Start in this directory Environment="KEY=value" # Set environment variables EnvironmentFile=/etc/myapp.conf # Read environment from file StandardOutput=journal # Send stdout to journal StandardError=journal # Send stderr to journal
[Install] Section - Installation Info
[Install] WantedBy=multi-user.target # Enable creates symlink to this target # Also=other.service # Also enable these services Alias=myapp.service # Alternative name
Common Service Types Explained
# Simple (most common) - systemd starts and tracks the process [Service] Type=simple ExecStart=/usr/bin/myapp # Forking - Traditional daemon that forks and exits [Service] Type=forking PIDFile=/run/myapp.pid ExecStart=/usr/bin/myapp --daemon # Oneshot - Run once and exit (like init scripts) [Service] Type=oneshot ExecStart=/usr/bin/setup-script RemainAfterExit=yes # Consider service active after exit # Notify - Service tells systemd when it's ready [Service] Type=notify ExecStart=/usr/bin/myapp --notify
Important Directives
# Security directives PrivateTmp=true # Service gets private /tmp NoNewPrivileges=true # Service cannot gain new privileges ProtectSystem=strict # Protect system directories ProtectHome=true # Protect home directories ReadWritePaths=/var/lib/myapp # Allow write only to specific paths # Resource limits LimitNOFILE=65536 # Max open files LimitNPROC=512 # Max processes LimitMEMLOCK=infinity # Max locked memory # Restart behavior RestartSec=10 # Wait 10 seconds before restart StartLimitInterval=60 # Reset failure count after 60 seconds StartLimitBurst=3 # Allow 3 failures before giving up # Timeouts TimeoutStartSec=30 # Timeout for starting TimeoutStopSec=10 # Timeout for stopping
🔧 Creating Custom Services
Why Create Custom Services?
You should create custom services when you want to:
Auto-start your applications at boot
Manage your applications with systemctl
Monitor your applications with journalctl
Restart automatically if they crash
Control resource usage (CPU, memory limits)
Example 1: Simple Python Web Application Service
# Create the application sudo mkdir -p /opt/myapp sudo nano /opt/myapp/app.py
/opt/myapp/app.py:
#!/usr/bin/env python3 from http.server import HTTPServer, SimpleHTTPRequestHandler import os class MyHandler(SimpleHTTPRequestHandler): def do_GET(self): if self.path == '/health': self.send_response(200) self.end_headers() self.wfile.write(b'OK') else: super().do_GET() os.chdir('/opt/myapp/html') server = HTTPServer(('0.0.0.0', 8080), MyHandler) print("Starting server on port 8080...") server.serve_forever()
# Make it executable sudo chmod +x /opt/myapp/app.py # Create HTML directory sudo mkdir -p /opt/myapp/html echo "<h1>My Application</h1>" | sudo tee /opt/myapp/html/index.html # Install Python if needed sudo apt install python3
Create the service unit file:
sudo nano /etc/systemd/system/myapp.service
/etc/systemd/system/myapp.service:
[Unit] Description=My Python Web Application Documentation=https://github.com/myusername/myapp After=network.target Wants=network.target [Service] Type=simple User=www-data Group=www-data WorkingDirectory=/opt/myapp ExecStart=/usr/bin/python3 /opt/myapp/app.py ExecReload=/bin/kill -s HUP $MAINPID ExecStop=/bin/kill -s TERM $MAINPID Restart=on-failure RestartSec=10 StandardOutput=journal StandardError=journal # Security PrivateTmp=true NoNewPrivileges=true ProtectSystem=strict ReadWritePaths=/opt/myapp # Resource limits LimitNOFILE=65536 # Timeouts TimeoutStartSec=30 TimeoutStopSec=10 [Install] WantedBy=multi-user.target
Enable and start the service:
# Reload systemd to recognize new service sudo systemctl daemon-reload # Enable to start at boot sudo systemctl enable myapp # Start the service sudo systemctl start myapp # Check status sudo systemctl status myapp # View logs sudo journalctl -u myapp -f # Test the application curl http://localhost:8080/ curl http://localhost:8080/health
Example 2: Node.js Application with Environment Variables
# Create application directory sudo mkdir -p /opt/nodeapp sudo nano /opt/nodeapp/app.js
/opt/nodeapp/app.js:
const http = require('http'); const hostname = process.env.HOST || '0.0.0.0'; const port = process.env.PORT || 3000; const server = http.createServer((req, res) => { if (req.url === '/health') { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('OK'); return; } res.statusCode = 200; res.setHeader('Content-Type', 'text/html'); res.end(` <!DOCTYPE html> <html> <head><title>Node App</title></head> <body> <h1>Node.js Application</h1> <p>Environment: ${process.env.NODE_ENV}</p> <p>Server: ${hostname}:${port}</p> </body> </html> `); }); server.listen(port, hostname, () => { console.log(`Server running at http://${hostname}:${port}/`); }); // Handle shutdown gracefully process.on('SIGTERM', () => { console.log('Received SIGTERM, shutting down gracefully...'); server.close(() => { console.log('Server closed'); process.exit(0); }); });
# Install Node.js if needed curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash - sudo apt install -y nodejs # Create environment file sudo nano /etc/nodeapp.conf
/etc/nodeapp.conf:
NODE_ENV=production PORT=3000 HOST=0.0.0.0 APP_SECRET=your-secret-key-here
Create the service:
sudo nano /etc/systemd/system/nodeapp.service
/etc/systemd/system/nodeapp.service:
[Unit] Description=Node.js Application Documentation=https://nodejs.org/ After=network.target Wants=network.target [Service] Type=simple User=nodeapp Group=nodeapp WorkingDirectory=/opt/nodeapp # Create user if doesn't exist ExecStartPre=/usr/sbin/useradd -r -s /usr/sbin/nologin nodeapp 2>/dev/null || true ExecStartPre=/bin/chown -R nodeapp:nodeapp /opt/nodeapp EnvironmentFile=/etc/nodeapp.conf ExecStart=/usr/bin/node /opt/nodeapp/app.js Restart=on-failure RestartSec=10 # Log to journal StandardOutput=journal StandardError=journal # Security PrivateTmp=true NoNewPrivileges=true ProtectSystem=strict ReadWritePaths=/opt/nodeapp # Resource limits LimitNOFILE=65536 LimitNPROC=512 # Socket activation (optional) # ListenStream=3000 [Install] WantedBy=multi-user.target
Manage the service:
# Reload and enable sudo systemctl daemon-reload sudo systemctl enable nodeapp sudo systemctl start nodeapp # Check status sudo systemctl status nodeapp # View logs sudo journalctl -u nodeapp -f # Test curl http://localhost:3000/ curl http://localhost:3000/health
Example 3: Backup Service with Timer (Scheduled Job)
Create backup script:
sudo nano /usr/local/bin/backup-system.sh
/usr/local/bin/backup-system.sh:
#!/bin/bash # Backup system script BACKUP_DIR="/backup" TIMESTAMP=$(date +%Y%m%d_%H%M%S) BACKUP_FILE="$BACKUP_DIR/backup-$TIMESTAMP.tar.gz" # Log function log() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a /var/log/backup.log } log "Starting backup..." # Create backup directory if it doesn't exist mkdir -p "$BACKUP_DIR" # Backup important directories tar -czf "$BACKUP_FILE" \ /etc \ /home \ /var/www 2>/dev/null || log "Warning: Some files could not be backed up" # Calculate size SIZE=$(du -h "$BACKUP_FILE" | cut -f1) log "Backup completed: $BACKUP_FILE ($SIZE)" # Clean old backups (keep last 7 days) find "$BACKUP_DIR" -name "backup-*.tar.gz" -mtime +7 -delete log "Cleanup completed"
# Make executable sudo chmod +x /usr/local/bin/backup-system.sh # Create backup directory sudo mkdir -p /backup
Create service unit file:
sudo nano /etc/systemd/system/backup.service
/etc/systemd/system/backup.service:
[Unit] Description=System Backup Service After=network.target [Service] Type=oneshot User=root Group=root ExecStart=/usr/local/bin/backup-system.sh StandardOutput=journal StandardError=journal [Install] WantedBy=multi-user.target
Create timer unit file (for scheduling):
sudo nano /etc/systemd/system/backup.timer
/etc/systemd/system/backup.timer:
[Unit] Description=Run backup daily at 2 AM Requires=backup.service [Timer] OnCalendar=daily Persistent=true [Install] WantedBy=timers.target
Enable and schedule:
# Reload systemd sudo systemctl daemon-reload # Enable and start timer (not the service!) sudo systemctl enable backup.timer sudo systemctl start backup.timer # Check timer status sudo systemctl status backup.timer # List all timers sudo systemctl list-timers --all # Run backup immediately (for testing) sudo systemctl start backup.service # Check logs sudo journalctl -u backup.service
🎯 Real-World Service Scenarios
Scenario 1: Multi-Service Application Stack
# Create a web application with database and cache # Directory structure sudo mkdir -p /opt/myapp/{bin,config,logs} # Create application components sudo nano /opt/myapp/bin/webapp.py sudo nano /opt/myapp/bin/worker.py sudo nano /opt/myapp/bin/scheduler.py
Create a target unit to group services:
sudo nano /etc/systemd/system/myapp.target
/etc/systemd/system/myapp.target:
[Unit] Description=My Application Stack Documentation=https://myapp.com/docs Requires=myapp-web.service myapp-worker.service myapp-redis.service After=network.target postgresql.service
Create individual services:
# Web service sudo nano /etc/systemd/system/myapp-web.service
/etc/systemd/system/myapp-web.service:
[Unit] Description=MyApp Web Server PartOf=myapp.target After=myapp-redis.service Requires=myapp-redis.service [Service] Type=simple User=myapp Group=myapp WorkingDirectory=/opt/myapp EnvironmentFile=/opt/myapp/config/production.env ExecStart=/usr/bin/gunicorn --bind 0.0.0.0:8000 webapp:app Restart=on-failure RestartSec=10 StandardOutput=journal StandardError=journal [Install] WantedBy=myapp.target
Create dependencies:
# Redis service (if not already installed) sudo nano /etc/systemd/system/myapp-redis.service
/etc/systemd/system/myapp-redis.service:
[Unit] Description=MyApp Redis Cache PartOf=myapp.target [Service] Type=simple User=redis Group=redis ExecStart=/usr/bin/redis-server /etc/redis/redis.conf Restart=always RestartSec=10 [Install] WantedBy=myapp.target
Manage the stack:
# Enable the target (enables all services) sudo systemctl enable myapp.target # Start the stack sudo systemctl start myapp.target # Check status of all services sudo systemctl status 'myapp*' # Stop entire stack sudo systemctl stop myapp.target # View logs for all services sudo journalctl -u 'myapp*' -f
Scenario 2: Service with Health Checks and Auto-Recovery
# Create service with health check sudo nano /etc/systemd/system/healthchecked.service
/etc/systemd/system/healthchecked.service:
[Unit] Description=Service with Health Checks After=network.target [Service] Type=simple User=appuser WorkingDirectory=/opt/myapp # Main application ExecStart=/opt/myapp/start.sh # Health check script (runs every 30 seconds) ExecStartPost=/bin/bash -c 'while true; do /opt/myapp/healthcheck.sh && sleep 30; done' # Restart policies Restart=on-failure RestartSec=5 StartLimitInterval=100 StartLimitBurst=5 # Timeouts TimeoutStartSec=30 TimeoutStopSec=30 # Watchdog (systemd monitors service) WatchdogSec=30 # Logging StandardOutput=journal StandardError=journal [Install] WantedBy=multi-user.target
Health check script:
sudo nano /opt/myapp/healthcheck.sh
#!/bin/bash # Health check script HEALTH_URL="http://localhost:8080/health" # Try to reach health endpoint if curl -f -s --max-time 5 "$HEALTH_URL" > /dev/null; then echo "Health check passed" exit 0 else echo "Health check failed" # Notify systemd that service needs restart systemd-notify WATCHDOG=1 exit 1 fi
Scenario 3: Development Service with Auto-Reload
# Service that watches for code changes and reloads sudo nano /etc/systemd/system/dev-app.service
/etc/systemd/system/dev-app.service:
[Unit] Description=Development Application with Auto-Reload After=network.target [Service] Type=simple User=developer Group=developer WorkingDirectory=/home/developer/app # Use a process manager that supports reload ExecStart=/usr/bin/nodemon --watch /home/developer/app --ext js,json app.js # Development-only settings Restart=always RestartSec=3 StandardOutput=journal StandardError=journal # Allow more open files for development LimitNOFILE=100000 # Don't apply strict security in development PrivateTmp=false [Install] WantedBy=multi-user.target
Scenario 4: Service Dependency Chain
# Services that must start in specific order # database.service -> cache.service -> app.service sudo nano /etc/systemd/system/database.service
/etc/systemd/system/database.service:
[Unit] Description=Database Service Before=cache.service [Service] Type=simple ExecStart=/usr/bin/start-database.sh Restart=on-failure [Install] WantedBy=multi-user.target
/etc/systemd/system/cache.service:
[Unit] Description=Cache Service After=database.service Before=app.service Requires=database.service [Service] Type=simple ExecStart=/usr/bin/start-cache.sh Restart=on-failure [Install] WantedBy=multi-user.target
/etc/systemd/system/app.service:
[Unit] Description=Main Application After=cache.service Requires=cache.service [Service] Type=simple ExecStart=/usr/bin/start-app.sh Restart=on-failure [Install] WantedBy=multi-user.target
💡 Best Practices for Service Management
1. Always Use Absolute Paths
# GOOD ExecStart=/usr/bin/myapp --config /etc/myapp.conf # BAD ExecStart=myapp --config myapp.conf
2. Set Appropriate User/Groups
# Never run as root unless absolutely necessary User=myappuser Group=myappgroup # Create the user if needed ExecStartPre=/usr/sbin/useradd -r -s /usr/sbin/nologin myappuser 2>/dev/null || true
3. Implement Proper Logging
StandardOutput=journal StandardError=journal # or StandardOutput=file:/var/log/myapp.log StandardError=file:/var/log/myapp.error.log
4. Set Resource Limits
LimitNOFILE=65536 LimitNPROC=512 LimitCORE=0 # Disable core dumps (unless debugging)
5. Configure Restart Policies
# For critical services Restart=always RestartSec=10 # For services that should stay dead if they fail Restart=on-failure StartLimitIntervalSec=600 StartLimitBurst=5
6. Add Security Hardening
PrivateTmp=true NoNewPrivileges=true ProtectSystem=strict ProtectHome=true ReadWritePaths=/var/lib/myapp
7. Test Before Deploying
# Test syntax sudo systemd-analyze verify /etc/systemd/system/myapp.service # Dry run sudo systemctl start myapp --dry-run # Check dependencies sudo systemctl list-dependencies myapp.service
8. Document Your Services
# Add documentation to unit files Documentation=man:myapp(8) Documentation=https://github.com/myorg/myapp/wiki # Create README sudo nano /etc/systemd/system/README.myapp
📋 Quick Reference Cheat Sheet
| Task | Command | Description |
|---|---|---|
| Start service | sudo systemctl start servicename | Start service now |
| Stop service | sudo systemctl stop servicename | Stop service |
| Restart service | sudo systemctl restart servicename | Restart service |
| Reload service | sudo systemctl reload servicename | Reload config |
| Enable at boot | sudo systemctl enable servicename | Enable auto-start |
| Disable at boot | sudo systemctl disable servicename | Disable auto-start |
| Check status | sudo systemctl status servicename | View service status |
| View logs | sudo journalctl -u servicename | View service logs |
| Follow logs | sudo journalctl -u servicename -f | Follow logs live |
| List services | sudo systemctl list-units --type=service | List all services |
| Check enabled | sudo systemctl is-enabled servicename | Check if enabled |
| Reload systemd | sudo systemctl daemon-reload | Reload unit files |
| Mask service | sudo systemctl mask servicename | Prevent starting |
| Unmask service | sudo systemctl unmask servicename | Remove mask |
| Failed services | sudo systemctl --failed | List failed services |
| List timers | sudo systemctl list-timers | List scheduled jobs |
| Analyze boot | systemd-analyze blame | Show slow services |
| Create service | sudo nano /etc/systemd/system/myservice.service | Create unit file |
🚀 Practice Exercises
Exercise 1: Create a Simple Web Server Service
# 1. Create a simple Python HTTP server cat > /tmp/simple-server.py << 'EOF' #!/usr/bin/env python3 from http.server import SimpleHTTPRequestHandler, HTTPServer import os os.chdir('/tmp') server = HTTPServer(('0.0.0.0', 9090), SimpleHTTPRequestHandler) print("Server running on port 9090") server.serve_forever() EOF chmod +x /tmp/simple-server.py # 2. Create service unit file sudo tee /etc/systemd/system/simple-server.service << 'EOF' [Unit] Description=Simple HTTP Server After=network.target [Service] Type=simple ExecStart=/usr/bin/python3 /tmp/simple-server.py Restart=on-failure RestartSec=5 [Install] WantedBy=multi-user.target EOF # 3. Enable and start sudo systemctl daemon-reload sudo systemctl enable simple-server sudo systemctl start simple-server sudo systemctl status simple-server # 4. Test curl http://localhost:9090
Exercise 2: Create a Timer Service
# 1. Create a script that runs periodically sudo tee /usr/local/bin/system-check.sh << 'EOF' #!/bin/bash echo "System check at $(date)" >> /var/log/system-check.log echo "Uptime: $(uptime)" >> /var/log/system-check.log echo "Disk: $(df -h / | tail -1)" >> /var/log/system-check.log EOF sudo chmod +x /usr/local/bin/system-check.sh # 2. Create service sudo tee /etc/systemd/system/system-check.service << 'EOF' [Unit] Description=System Check Service [Service] Type=oneshot ExecStart=/usr/local/bin/system-check.sh EOF # 3. Create timer sudo tee /etc/systemd/system/system-check.timer << 'EOF' [Unit] Description=Run system check every 5 minutes [Timer] OnCalendar=*:0/5 Persistent=true [Install] WantedBy=timers.target EOF # 4. Enable timer sudo systemctl daemon-reload sudo systemctl enable system-check.timer sudo systemctl start system-check.timer sudo systemctl list-timers | grep system-check
Exercise 3: Service with Environment Variables
# 1. Create environment file sudo tee /etc/myapp.env << 'EOF' APP_NAME=TestApplication APP_PORT=8888 DEBUG=false EOF # 2. Create test script sudo tee /opt/test-app.sh << 'EOF' #!/bin/bash echo "Starting $APP_NAME on port $APP_PORT" echo "Debug mode: $DEBUG" while true; do echo "Running... $(date)" sleep 10 done EOF sudo chmod +x /opt/test-app.sh # 3. Create service sudo tee /etc/systemd/system/test-app.service << 'EOF' [Unit] Description=Test Application with Environment [Service] EnvironmentFile=/etc/myapp.env ExecStart=/opt/test-app.sh Restart=always [Install] WantedBy=multi-user.target EOF # 4. Start and test sudo systemctl daemon-reload sudo systemctl start test-app sudo systemctl status test-app sudo journalctl -u test-app -f
Exercise 4: Analyze and Optimize Service Boot
# 1. Check current boot time systemd-analyze # 2. Find slowest services systemd-analyze blame # 3. Check critical chain systemd-analyze critical-chain # 4. Check service dependencies for a slow service sudo systemctl list-dependencies nginx.service --reverse # 5. Disable a non-essential service sudo systemctl disable bluetooth.service sudo systemctl mask bluetooth.service # 6. Create a custom target for faster boot sudo tee /etc/systemd/system/fast-boot.target << 'EOF' [Unit] Description=Fast Boot Target Requires=basic.target Conflicts=shutdown.target Before=multi-user.target AllowIsolate=yes EOF # 7. Switch to it sudo systemctl isolate fast-boot.target
🔗 Master Service Management with Hands-on Labs
Service management is critical for running reliable applications. Understanding systemd allows you to create robust, maintainable services.
👉 Practice service creation, management, and optimization in our interactive labs at:
https://devops.trainwithsky.com/
Our platform provides:
Real systemd environments to practice
Service creation exercises
Dependency management scenarios
Production service templates
Troubleshooting challenges
Frequently Asked Questions
Q: Should I use .service or .target files?
A: Use .service for individual services, .target for groups of services that should start together.
Q: What's the difference between Wants and Requires?
A: Requires = hard dependency (stops if dependency stops). Wants = soft dependency (starts after, but doesn't stop if dependency stops).
Q: How do I debug a service that won't start?
A: 1) sudo systemctl status servicename 2) sudo journalctl -u servicename 3) Test command manually 4) Check permissions and paths.
Q: Can I convert old init scripts to systemd?
A: Yes! Use systemd-sysv-generator or create a .service file that calls the init script.
Q: What's better: Type=simple or Type=forking?
A: Use Type=simple for modern applications that don't fork. Use Type=forking for traditional daemons that fork and exit.
Q: How do I run a service as a non-root user?
A: Set User= and Group= in [Service] section, and ensure files have correct permissions.
Q: Can systemd services talk to each other?
A: Yes, through sockets, D-Bus, or standard IPC. Use socket activation for efficient communication.
Having issues with services or need help creating a custom service? Share your service file in the comments below! 💬
Comments
Post a Comment