Services with systemctl

systemctl starts, stops and inspects background services managed by systemd.

Syntaxsystemctl [start|stop|restart|enable|status] service

Long-running background programs such as web servers and databases are managed as services (also called units) by systemd. You control them with systemctl.

The everyday commands

  • systemctl status nginx — is it running? Show recent logs.
  • sudo systemctl start nginx — start it now.
  • sudo systemctl stop nginx — stop it.
  • sudo systemctl restart nginx — stop then start.
  • sudo systemctl enable nginx — start automatically at boot.

Most of these need sudo because they change the system's state; status usually does not.

Example

Example · bash
# Check whether a service is running
systemctl status ssh
# Active: active (running) since Mon ...

# Start it and make it boot automatically
sudo systemctl start nginx
sudo systemctl enable nginx

# Apply new config with a restart
sudo systemctl restart nginx

When to use it

  • A sysadmin uses 'systemctl status nginx' to check whether the web server is active and view its latest log lines after a config change.
  • A DevOps engineer runs 'systemctl enable --now myapp.service' to both start a service immediately and configure it to start on boot.
  • A developer writes a custom systemd unit file so their application restarts automatically if it crashes.

More examples

Start, stop, and check status

Shows the four fundamental systemctl commands for controlling a service's running state.

Example · bash
# Check if nginx is running
systemctl status nginx

# Start the service
sudo systemctl start nginx

# Stop the service
sudo systemctl stop nginx

# Restart after config change
sudo systemctl restart nginx

Enable service on boot

Contrasts enable (boot-time) vs start (immediate) and shows --now to do both in a single command.

Example · bash
# Enable to start at boot
sudo systemctl enable nginx

# Disable from starting at boot
sudo systemctl disable nginx

# Enable AND start immediately in one command
sudo systemctl enable --now nginx

Write a custom service unit

Shows a minimal systemd unit file with auto-restart on failure, running as a non-root user.

Example · bash
# /etc/systemd/system/myapp.service
[Unit]
Description=My Node.js App
After=network.target

[Service]
ExecStart=/usr/bin/node /opt/myapp/server.js
Restart=on-failure
User=nodeuser

[Install]
WantedBy=multi-user.target

Discussion

  • Be the first to comment on this lesson.