⚙️ Systemctl & Service Management di Linux (systemd)

systemd adalah init system modern di banyak distro Linux (Debian/Ubuntu, RHEL/CentOS/Alma/Rocky, Fedora, openSUSE).
systemctl adalah CLI utama untuk mengelola service (unit): start/stop, enable/disable saat boot, melihat status dan log, serta membuat unit kustom.


🔹 Konsep Inti systemd

  • Unit: objek yang dikelola systemd. Tipe umum:
    • .service (proses/aplikasi)
    • .socket (socket activation)
    • .timer (penjadwalan, pengganti cron)
    • .target (kumpulan unit, mode runlevel)
    • .mount / .automount
    • .path, .device, .slice, .scope
  • Lokasi unit file (prioritas dari atas ke bawah):
    1. /etc/systemd/system/local override (persisten)
    2. /usr/lib/systemd/system/ — file dari paket (RHEL/Fedora/Arch)
    3. /lib/systemd/system/ — file dari paket (Debian/Ubuntu)
  • Override/Drop-in: folder /etc/systemd/system/<unit>.d/*.conf untuk menimpa sebagian konfigurasi tanpa menyentuh file paket.
  • Section standar di unit .service:
    • [Unit] → metadata & dependency
    • [Service] → eksekusi & perilaku proses
    • [Install] → integrasi enable/disable (mis. WantedBy=)

🔹 Operasional Harian (Cheat Sheet)

Status & Lifecycle

systemctl status nginx.service
systemctl start nginx.service
systemctl stop nginx.service
systemctl restart nginx.service
systemctl reload nginx.service      # kirim SIGHUP jika didukung

Enable/Disable saat boot

systemctl enable nginx.service
systemctl disable nginx.service
systemctl is-enabled nginx.service

Cek aktif/failed

systemctl is-active nginx.service
systemctl is-failed nginx.service

List service & unit file

systemctl list-units --type=service
systemctl list-unit-files --type=service

Log service (journal)

journalctl -u nginx.service --since "today"
journalctl -u nginx.service -f        # follow realtime
journalctl -xeu nginx.service         # detail error + context

Reload konfigurasi systemd (setiap ubah unit file)

sudo systemctl daemon-reload

🔹 Membuat Service Kustom

1) Contoh unit sederhana

Buat file /etc/systemd/system/myapp.service:

[Unit]
Description=MyApp Web API
After=network.target
Wants=network-online.target

[Service]
Type=simple
WorkingDirectory=/opt/myapp
ExecStart=/usr/bin/dotnet /opt/myapp/MyApp.dll
Restart=on-failure
RestartSec=5
User=myapp
Group=myapp
Environment=ASPNETCORE_URLS=http://0.0.0.0:5000

[Install]
WantedBy=multi-user.target

Aktifkan:

sudo systemctl daemon-reload
sudo systemctl enable --now myapp.service
systemctl status myapp.service
journalctl -u myapp.service -f

2) Override tanpa mengubah file paket

sudo systemctl edit nginx.service

Akan membuat /etc/systemd/system/nginx.service.d/override.conf. Contoh isi:

[Service]
Environment="WORKERS=4"

3) Direktif penting pada [Service]

  • Type= simple|forking|oneshot|notify|dbus
  • ExecStart=, ExecStartPre=, ExecStartPost=
  • ExecReload=, ExecStop=
  • Restart= always|on-failure|on-abnormal|on-watchdog|no
  • RestartSec=, TimeoutStartSec=, TimeoutStopSec=
  • User=, Group=, WorkingDirectory=
  • Environment=, **EnvironmentFile=/etc/default/myapp(Debian) atau/etc/sysconfig/myapp` (RHEL)
  • UMask= 0027 (contoh default permission yang lebih ketat)

🔹 Hardening Service (Keamanan)

Tambahkan pada [Service] untuk membatasi dampak kompromi proses:

NoNewPrivileges=true
ProtectSystem=strict        # rootfs read-only; gunakan ReadWritePaths= jika perlu tulis
ProtectHome=true            # blok akses /home, /root, /run/user
PrivateTmp=true             # /tmp terisolasi
PrivateDevices=true         # blok akses device mentah
CapabilityBoundingSet=      # kosongkan untuk drop semua capability root
AmbientCapabilities=        # whitelist capability yang dibutuhkan, mis. CAP_NET_BIND_SERVICE
ReadWritePaths=/var/lib/myapp /var/log/myapp
RestrictAddressFamilies=AF_INET AF_INET6
RestrictNamespaces=yes
SystemCallFilter=@system-service
LockPersonality=yes
MemoryMax=500M
CPUQuota=80%
TasksMax=1024

Analisis tingkat keamanan unit:

systemd-analyze security myapp.service

🔹 Timer (Pengganti Cron yang Terkelola)

Buat service pekerjaan backup

/etc/systemd/system/backup-db.service

[Unit]
Description=Backup Database harian

[Service]
Type=oneshot
ExecStart=/usr/local/bin/backup_db.sh

Buat timer-nya

/etc/systemd/system/backup-db.timer

[Unit]
Description=Jalankan backup-db.service setiap hari

[Timer]
OnCalendar=daily
Persistent=true            # jalankan yang terlewat saat sistem mati
Unit=backup-db.service

[Install]
WantedBy=timers.target

Aktifkan:

sudo systemctl daemon-reload
sudo systemctl enable --now backup-db.timer
systemctl list-timers

Contoh OnCalendar: Mon..Fri 08:00, *:0/15 (tiap 15 menit), weekly, 2025-09-01 23:00.


🔹 Socket Activation (Start on-demand)

/etc/systemd/system/echo.socket

[Unit]
Description=Echo TCP socket

[Socket]
ListenStream=12345
Accept=no

[Install]
WantedBy=sockets.target

/etc/systemd/system/echo.service

[Unit]
Description=Echo server

[Service]
ExecStart=/usr/local/bin/echo-server --port=12345

Aktifkan:

sudo systemctl daemon-reload
sudo systemctl enable --now echo.socket
systemctl status echo.socket

Service akan start hanya saat ada koneksi ke port 12345.


🔹 Target & Mode Sistem

  • Lihat target aktif: systemctl get-default
  • Ubah default: sudo systemctl set-default multi-user.target (server) / graphical.target (desktop)
  • Mode rescue: sudo systemctl rescue
  • Mode emergency: sudo systemctl emergency
  • Analisis boot:
    systemd-analyze blame
    systemd-analyze critical-chain

🔹 User Service (Tanpa root)

Systemd juga berjalan per-user:

systemctl --user enable --now myapp.service
journalctl --user -u myapp.service -f

Agar tetap hidup setelah logout, aktifkan lingering:

sudo loginctl enable-linger <username>

Unit user disimpan di: ~/.config/systemd/user/


🔎 Troubleshooting Cepat

systemctl status <unit>
journalctl -xeu <unit>                  # error detail
systemctl cat <unit>                    # lihat isi unit + drop-in
systemd-analyze verify <path/to/unit>   # validasi sintaks unit
systemd-delta                           # lihat perbedaan override
systemctl show -p ExecMainStatus <unit> # exit code eksekusi

Jika mengubah unit/override, selalu:

sudo systemctl daemon-reload

✅ Best Practices

  • Simpan kustomisasi di /etc/systemd/system/ atau drop-in .d/, hindari edit file bawaan paket.
  • Gunakan EnvironmentFile= untuk konfigurasi yang mudah diubah tanpa restart biner.
  • Set Restart= dan RestartSec= sesuai karakter aplikasi (service resilien).
  • Aktifkan sandboxing (ProtectSystem, NoNewPrivileges, dsb.) untuk memperkecil risiko.
  • Gunakan timer untuk job terjadwal; lebih mudah diawasi ketimbang cron.
  • Pantau log dengan journalctl -u <service> -f saat debugging.
  • Dokumentasikan dependency (After=, Requires=, Wants=) agar urutan start jelas.

📌 Ringkasan

  • systemctl adalah alat utama untuk mengelola lifecycle service di Linux modern.
  • Pahami lokasi unit, directive utama, logging via journalctl, dan fitur timer/socket untuk operasi yang rapi dan terukur.
  • Dengan hardening yang tepat, service menjadi lebih aman dan andal di production.