Skip to main content

Linux Services & Daemons Management Guide - DevOps

 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

  1. System Services - Run at boot, essential for system operation

  2. Network Services - Handle network connections (SSH, HTTP, etc.)

  3. User Services - Started when user logs in

  4. 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/

bash
sudo /etc/init.d/nginx start
sudo service nginx restart

Modern way (systemd): All services managed by systemctl

bash
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

bash
# 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

bash
# 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

bash
# 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

bash
# 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

bash
# 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

bash
# 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

bash
# 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

bash
# 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

bash
# 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

bash
# 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:

bash
# View nginx service unit file
cat /lib/systemd/system/nginx.service

Example nginx.service:

ini
[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

ini
[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

ini
[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

ini
[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

ini
# 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

ini
# 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:

  1. Auto-start your applications at boot

  2. Manage your applications with systemctl

  3. Monitor your applications with journalctl

  4. Restart automatically if they crash

  5. Control resource usage (CPU, memory limits)

Example 1: Simple Python Web Application Service

bash
# Create the application
sudo mkdir -p /opt/myapp
sudo nano /opt/myapp/app.py

/opt/myapp/app.py:

python
#!/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()
bash
# 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:

bash
sudo nano /etc/systemd/system/myapp.service

/etc/systemd/system/myapp.service:

ini
[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:

bash
# 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

bash
# Create application directory
sudo mkdir -p /opt/nodeapp
sudo nano /opt/nodeapp/app.js

/opt/nodeapp/app.js:

javascript
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);
  });
});
bash
# 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:

bash
NODE_ENV=production
PORT=3000
HOST=0.0.0.0
APP_SECRET=your-secret-key-here

Create the service:

bash
sudo nano /etc/systemd/system/nodeapp.service

/etc/systemd/system/nodeapp.service:

ini
[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:

bash
# 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:

bash
sudo nano /usr/local/bin/backup-system.sh

/usr/local/bin/backup-system.sh:

bash
#!/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"
bash
# Make executable
sudo chmod +x /usr/local/bin/backup-system.sh

# Create backup directory
sudo mkdir -p /backup

Create service unit file:

bash
sudo nano /etc/systemd/system/backup.service

/etc/systemd/system/backup.service:

ini
[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):

bash
sudo nano /etc/systemd/system/backup.timer

/etc/systemd/system/backup.timer:

ini
[Unit]
Description=Run backup daily at 2 AM
Requires=backup.service

[Timer]
OnCalendar=daily
Persistent=true

[Install]
WantedBy=timers.target

Enable and schedule:

bash
# 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

bash
# 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:

bash
sudo nano /etc/systemd/system/myapp.target

/etc/systemd/system/myapp.target:

ini
[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:

bash
# Web service
sudo nano /etc/systemd/system/myapp-web.service

/etc/systemd/system/myapp-web.service:

ini
[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:

bash
# Redis service (if not already installed)
sudo nano /etc/systemd/system/myapp-redis.service

/etc/systemd/system/myapp-redis.service:

ini
[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:

bash
# 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

bash
# Create service with health check
sudo nano /etc/systemd/system/healthchecked.service

/etc/systemd/system/healthchecked.service:

ini
[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:

bash
sudo nano /opt/myapp/healthcheck.sh
bash
#!/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

bash
# Service that watches for code changes and reloads
sudo nano /etc/systemd/system/dev-app.service

/etc/systemd/system/dev-app.service:

ini
[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

bash
# 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:

ini
[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:

ini
[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:

ini
[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

ini
# GOOD
ExecStart=/usr/bin/myapp --config /etc/myapp.conf

# BAD
ExecStart=myapp --config myapp.conf

2. Set Appropriate User/Groups

ini
# 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

ini
StandardOutput=journal
StandardError=journal
# or
StandardOutput=file:/var/log/myapp.log
StandardError=file:/var/log/myapp.error.log

4. Set Resource Limits

ini
LimitNOFILE=65536
LimitNPROC=512
LimitCORE=0  # Disable core dumps (unless debugging)

5. Configure Restart Policies

ini
# 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

ini
PrivateTmp=true
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=/var/lib/myapp

7. Test Before Deploying

bash
# 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

bash
# 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

TaskCommandDescription
Start servicesudo systemctl start servicenameStart service now
Stop servicesudo systemctl stop servicenameStop service
Restart servicesudo systemctl restart servicenameRestart service
Reload servicesudo systemctl reload servicenameReload config
Enable at bootsudo systemctl enable servicenameEnable auto-start
Disable at bootsudo systemctl disable servicenameDisable auto-start
Check statussudo systemctl status servicenameView service status
View logssudo journalctl -u servicenameView service logs
Follow logssudo journalctl -u servicename -fFollow logs live
List servicessudo systemctl list-units --type=serviceList all services
Check enabledsudo systemctl is-enabled servicenameCheck if enabled
Reload systemdsudo systemctl daemon-reloadReload unit files
Mask servicesudo systemctl mask servicenamePrevent starting
Unmask servicesudo systemctl unmask servicenameRemove mask
Failed servicessudo systemctl --failedList failed services
List timerssudo systemctl list-timersList scheduled jobs
Analyze bootsystemd-analyze blameShow slow services
Create servicesudo nano /etc/systemd/system/myservice.serviceCreate unit file

🚀 Practice Exercises

Exercise 1: Create a Simple Web Server Service

bash
# 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

bash
# 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

bash
# 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

bash
# 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

Popular posts from this blog

Introduction to Terraform – The Future of Infrastructure as Code

  Introduction to Terraform – The Future of Infrastructure as Code In today’s fast-paced DevOps world, managing infrastructure manually is outdated . This is where Terraform comes in—a powerful Infrastructure as Code (IaC) tool that allows you to define, provision, and manage cloud infrastructure efficiently . Whether you're working with AWS, Azure, Google Cloud, or on-premises servers , Terraform provides a declarative, automation-first approach to infrastructure deployment. Shape Your Future with AI & Infinite Knowledge...!! Read In-Depth Tech & Self-Improvement Blogs http://www.skyinfinitetech.com Watch Life-Changing Videos on YouTube https://www.youtube.com/@SkyInfinite-Learning Transform Your Skills, Business & Productivity – Join Us Today! In today’s digital-first world, agility and automation are no longer optional—they’re essential. Companies across the globe are rapidly shifting their operations to the cloud to keep up with the pace of innovatio...

📊 Monitoring & Logging in Kubernetes – Tools like Prometheus, Grafana, and Fluentd

  Monitoring & Logging in Kubernetes – Tools like Prometheus, Grafana, and Fluentd Monitoring and logging are essential for maintaining a healthy and well-performing Kubernetes cluster. In this guide, we’ll cover why monitoring is important, key monitoring tools like Prometheus and Grafana, and logging tools like Fluentd to help you gain visibility into your cluster’s performance and logs. Shape Your Future with AI & Infinite Knowledge...!! Want to Generate Text-to-Voice, Images & Videos? http://www.ai.skyinfinitetech.com Read In-Depth Tech & Self-Improvement Blogs http://www.skyinfinitetech.com Watch Life-Changing Videos on YouTube https://www.youtube.com/@SkyInfinite-Learning Transform Your Skills, Business & Productivity – Join Us Today! 🚀 Introduction In today’s fast-paced cloud-native environment, Kubernetes has emerged as the de-facto container orchestration platform. But deploying and managing applications in Kubernetes is just half the ba...

🔒 Kubernetes Security – RBAC, Network Policies, and Secrets Management

  Kubernetes Security – RBAC, Network Policies, and Secrets Management Security is a critical aspect of managing Kubernetes clusters. In this guide, we'll cover essential security mechanisms like Role-Based Access Control (RBAC) , Network Policies , and Secrets Management to help you secure your Kubernetes environment effectively. Shape Your Future with AI & Infinite Knowledge...!! Want to Generate Text-to-Voice, Images & Videos? http://www.ai.skyinfinitetech.com Read In-Depth Tech & Self-Improvement Blogs http://www.skyinfinitetech.com Watch Life-Changing Videos on YouTube https://www.youtube.com/@SkyInfinite-Learning Transform Your Skills, Business & Productivity – Join Us Today! 🚀 Introduction: Why Kubernetes Security Is Non-Negotiable As Kubernetes becomes the backbone of modern cloud-native infrastructure, security is no longer optional—it’s mission-critical . With multiple moving parts like containers, pods, services, nodes, and more, Kuberne...