Mastering systemd: essential commands

Mascote do LinuxPro operando o painel de controle do systemd

Like it or not, systemd is the init system for practically every current distribution — Ubuntu, Debian, Fedora, Arch, openSUSE. Mastering half a dozen of its commands covers 90% of everyday service management. Here are the essentials, straight to the point.

Managing services

systemctl status nginx      # estado, PID, últimas linhas de log
sudo systemctl start nginx
sudo systemctl stop nginx
sudo systemctl restart nginx
sudo systemctl reload nginx # recarrega config sem derrubar conexões

sudo systemctl enable nginx   # inicia no boot
sudo systemctl disable nginx
sudo systemctl enable --now nginx  # ativa no boot E inicia agora

Logs with journalctl

The journal is the sysadmin's best friend:

journalctl -u nginx              # todos os logs do serviço
journalctl -u nginx -f           # acompanhar em tempo real (tail -f)
journalctl -u nginx --since "1 hour ago"
journalctl -p err -b             # só erros desde o último boot
journalctl --disk-usage          # quanto o journal ocupa em disco

Boot diagnostics

systemd-analyze                # tempo total de boot
systemd-analyze blame          # quem demorou mais
systemctl list-units --failed  # o que falhou

Timers: systemd's cron

systemctl list-timers          # agendamentos ativos e próximas execuções

Creating your own service

Any script becomes a service with a file in /etc/systemd/system/meuapp.service:

[Unit]
Description=Minha aplicação
After=network.target

[Service]
User=www-data
WorkingDirectory=/opt/meuapp
ExecStart=/opt/meuapp/run.sh
Restart=on-failure

[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl enable --now meuapp

The Restart=on-failure alone makes this post worthwhile: your service restarts automatically if it crashes.

Bookmark this post — it's the kind of reference you'll open every week.