One place for hosting & domains

      systemd

      Cara Menggunakan Systemctl untuk Mengelola Layanan dan Unit Systemd


      Pengantar

      Systemd adalah sistem init dan pengelola sistem yang secara luas telah menjadi standar baru untuk berbagai distribusi Linux. Karena digunakan secara luas, memahami systemd akan mengatasi banyak masalah, karena ini akan membuat pengelolaan server menjadi jauh lebih mudah. Mempelajari dan memanfaatkan berbagai alat dan daemon yang meliputi systemd akan membantu Anda menghargai kehebatan, fleksibilitas, dan kemampuan yang diberikannya dengan lebih baik, atau setidaknya membantu Anda melakukan pekerjaan tanpa banyak kesulitan.

      Dalam panduan ini, kita akan membahas perintah systemctl, yang merupakan alat manajemen pusat untuk mengontrol sistem init. Kita akan membahas cara mengelola layanan, memeriksa status, mengubah keadaan sistem, dan menangani berkas konfigurasi.

      Harap diperhatikan bahwa meskipun systemd telah menjadi sistem init asali untuk banyak distribusi Linux, tetapi tidak diterapkan secara universal ke semua distribusi. Saat mengikuti tutorial ini, jika terminal Anda memberikan keluaran pesan kesalahan bash: systemctl is not installed, kemungkinan mesin Anda menginstal sistem init yang berbeda.

      Manajemen Layanan

      Kegunaan mendasar dari sistem init adalah menginisialisasi komponen yang harus dimulai setelah kernel Linux melakukan boot (biasanya dikenal dengan komponen “userland”). Sistem init juga digunakan untuk mengelola layanan dan daemon bagi server di titik apa pun selama sistem dijalankan. Dengan mengingat hal itu, kita akan mulai dengan beberapa operasi manajemen layanan dasar.

      Di systemd, target sebagian besar tindakan adalah “unit”, yakni sumber daya yang diketahui cara pengelolaannya oleh systemd. Unit dikelompokkan menurut tipe sumber daya yang diwakilinya dan didefinisikan bersama berkas yang dikenal dengan berkas unit. Tipe setiap unit dapat ditebak dari akhiran di belakang berkas.

      Untuk tugas manajemen layanan, unit target akan berupa unit layanan, yang memiliki berkas unit dengan akhiran .service. Namun, untuk kebanyakan perintah manajemen layanan, Anda sebenarnya dapat menanggalkan akhiran .service, karena systemd sudah cukup cerdas untuk mengetahui bahwa Anda mungkin ingin mengoperasikan suatu layanan saat menggunakan perintah manajemen layanan.

      Memulai dan Menghentikan Layanan

      Untuk memulai layanan systemd, yang mengeksekusi instruksi dalam berkas unit layanan, gunakan perintah start. Jika menjalankan sebagai pengguna non-root, Anda akan perlu menggunakan sudo karena ini akan memengaruhi keadaan sistem operasi:

      • sudo systemctl start application.service

      Seperti yang kami sebutkan di atas, systemd tahu untuk mencari berkas *.service untuk perintah manajemen layanan, sehingga perintah dapat diketikkan semudah ini:

      • sudo systemctl start application

      Meskipun Anda mungkin menggunakan format di atas untuk administrasi umum, demi kejelasan, kita akan menggunakan akhiran .service untuk perintah selebihnya, agar target operasi kita lebih jelas.

      Untuk menghentikan layanan yang sedang berjalan, Anda dapat menggunakan perintah stop sebagai gantinya:

      • sudo systemctl stop application.service

      Memulai Ulang dan Memuat Ulang

      Untuk memulai ulang layanan yang sedang berjalan, Anda dapat menggunakan perintah restart:

      • sudo systemctl restart application.service

      Jika aplikasi tersebut dapat memuat ulang berkas konfigurasinya (tanpa memulai ulang), Anda dapat memberikan perintah reload untuk memulai proses:

      • sudo systemctl reload application.service

      Jika tidak yakin apakah layanan memiliki fungsionalitas untuk memuat ulang konfigurasinya, Anda dapat memberikan perintah reload-or-restart. Perintah ini akan memuat ulang konfigurasi jika tersedia. Jika tidak, perintah ini akan memulai ulang layanan sehingga konfigurasi baru akan diambil:

      • sudo systemctl reload-or-restart application.service

      Mengaktifkan dan Menonaktifkan Layanan

      Perintah di atas berguna untuk memulai atau menghentikan layanan selama sesi yang berjalan saat ini. Untuk memberi tahu systemd agar memulai layanan secara otomatis saat boot, Anda harus mengaktifkannya.

      Untuk memulai layanan saat boot, gunakan perintah enable:

      • sudo systemctl enable application.service

      Ini akan membuat tautan simbolis dari salinan berkas layanan sistem (biasanya di /lib/systemd/system atau /etc/systemd/system) ke dalam lokasi di diska tempat systemd mencari berkas autostart (biasanya /etc/systemd/system/some_target.target.wants. Kita akan membahas targetnya nanti dalam panduan ini).

      Untuk menonaktifkan layanan agar tidak dimulai secara otomatis, Anda dapat mengetikkan:

      • sudo systemctl disable application.service

      Ini akan menghapus tautan simbolis yang menandakan bahwa layanan harus dimulai secara otomatis.

      Ingatlah bahwa mengaktifkan layanan tidak akan memulainya di sesi saat ini. Jika Anda ingin memulai layanan dan juga mengaktifkannya saat boot, Anda harus memberikan perintah start dan enable.

      Memeriksa Status Layanan

      Untuk memeriksa status layanan di sistem, Anda dapat menggunakan perintah status:

      • systemctl status application.service

      Perintah ini akan memberi tahu Anda keadaan layanan, hierarki cgroup, dan beberapa baris log pertama.

      Misalnya, saat memeriksa status server Nginx, Anda mungkin melihat keluaran seperti ini:

      Output

      ● nginx.service - A high performance web server and a reverse proxy server Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: disabled) Active: active (running) since Tue 2015-01-27 19:41:23 EST; 22h ago Main PID: 495 (nginx) CGroup: /system.slice/nginx.service ├─495 nginx: master process /usr/bin/nginx -g pid /run/nginx.pid; error_log stderr; └─496 nginx: worker process Jan 27 19:41:23 desktop systemd[1]: Starting A high performance web server and a reverse proxy server... Jan 27 19:41:23 desktop systemd[1]: Started A high performance web server and a reverse proxy server.

      Ini memberikan gambaran bagus tentang status aplikasi saat ini, yang memberi tahu Anda masalah dan tindakan yang mungkin diperlukan.

      Ada juga metode untuk memeriksa keadaan tertentu. Misalnya, untuk memeriksa agar tahu apakah suatu unit sedang aktif (berjalan), Anda dapat menggunakan perintah is-active:

      • systemctl is-active application.service

      Ini akan menunjukkan keadaan unit saat ini, yang biasanya berupa active atau inactive. Kode yang keluar akan “0” jika aktif, sehingga membuat hasilnya jadi lebih mudah diurai dalam skrip shell.

      Untuk melihat apakah unit diaktifkan, Anda dapat menggunakan perintah is-enabled:

      • systemctl is-enabled application.service

      Ini akan memberikan keluaran apakah layanan enabled atau disabled dan akan menetapkan lagi kode keluar ke “0” atau “1”, tergantung jawaban terhadap pertanyaan perintah.

      Pemeriksaan ketiga adalah apakah unit dalam keadaan gagal. Ini menandakan adanya masalah saat memulai unit tersebut:

      • systemctl is-failed application.service

      Hasilnya akan menjadi active jika berjalan dengan benar atau failed jika terjadi kesalahan. Jika unit sengaja dihentikan, hasilnya mungkin akan berupa unknown atau inactive. Status keluar “0” menandakan terjadi suatu kegagalan dan status keluar “1” menandakan status lainnya.

      Gambaran Umum Keadaan Sistem

      Sejauh ini, perintah berguna untuk mengelola layanan tunggal, tetapi tidak terlalu berguna untuk mempelajari keadaan sistem saat ini. Ada sejumlah sejumlah perintah systemctl yang memberikan informasi ini.

      Menampilkan Daftar Unit Saat Ini

      Untuk melihat daftar semua unit aktif yang diketahui systemd, kita dapat menggunakan perintah list-units:

      Perintah ini akan menampilkan semua unit systemd yang saat ini aktif di sistem. Keluarannya akan terlihat seperti ini:

      Output

      UNIT LOAD ACTIVE SUB DESCRIPTION atd.service loaded active running ATD daemon avahi-daemon.service loaded active running Avahi mDNS/DNS-SD Stack dbus.service loaded active running D-Bus System Message Bus dcron.service loaded active running Periodic Command Scheduler dkms.service loaded active exited Dynamic Kernel Modules System [email protected] loaded active running Getty on tty1 . . .

      Keluarannya memiliki kolom berikut:

      • UNIT: Nama unit systemd
      • LOAD: Apakah konfigurasi unit telah diurai oleh systemd. Konfigurasi unit yang dimuat tersimpan dalam memori.
      • ACTIVE: Ringkasan keadaan apakah unit aktif. Ini biasanya cara yang cukup mendasar untuk mengetahui apakah unit berhasil dimulai atau tidak.
      • SUB: Ini tingkat keadaan lebih rendah yang menunjukkan informasi lebih detail tentang unit. Ini seringkali bervariasi menurut tipe unit, keadaan, dan metode aktual unit yang dijalankan.
      • DESCRIPTION: Deskripsi teks singkat tentang apa yang dilakukan unit.

      Karena perintah list-units hanya menampilkan unit aktif secara asali, semua entri di atas akan menampilkan loaded dalam kolom LOAD dan active dalam kolom ACTIVE. Tampilan ini sebenarnya adalah perilaku asali systemctl bila dipanggil tanpa perintah tambahan, sehingga Anda akan melihat hal yang sama jika memanggil systemctl tanpa argumen:

      Kita dapat menyuruh systemctl agar mengeluarkan informasi yang berbeda dengan memberikan bendera tambahan. Misalnya, untuk melihat semua unit yang telah dimuat (atau berupaya dimuat) oleh systemd , entah saat ini aktif atau tidak, Anda dapat menggunakan bendera --all, seperti ini:

      • systemctl list-units --all

      Ini akan menampilkan unit yang telah dimuat atau berupaya dimuat oleh systemd, terlepas dari keadaannya saat ini di sistem. Beberapa unit menjadi tidak aktif setelah berjalan, dan beberapa unit yang berupaya dimuat oleh systemd mungkin tidak ditemukan pada diska.

      Anda dapat menggunakan bendera lain untuk menyaring hasil ini. Misalnya, kita dapat menggunakan bendera --state= untuk menandai keadaan LOAD, ACTIVE, atau SUB yang ingin kita lihat. Anda harus mempertahankan bendera --all agar systemctl mengizinkan unit nonaktif untuk ditampilkan:

      • systemctl list-units --all --state=inactive

      Filter umum lainnya adalah filter --type=. Kita dapat menyuruh systemctl agar hanya menampilkan unit dengan tipe yang kita minati. Misalnya, untuk melihat unit layanan aktif saja, kita dapat menggunakan:

      • systemctl list-units --type=service

      Menampilkan Daftar Semua Berkas Unit

      Perintah list-units hanya menampilkan unit yang telah berupaya diurai dan dimuat systemd ke dalam memori. Karena systemd hanya akan membaca unit yang dianggapnya perlu, maka tidak perlu menyertakan semua unit yang tersedia di sistem. Untuk melihat setiap berkas unit yang tersedia dalam jalur systemd, termasuk berkas yang tidak berupaya dimuat oleh systemd, Anda dapat menggunakan perintah list-unit-files sebagai gantinya:

      • systemctl list-unit-files

      Unit adalah representasi dari sumber daya yang diketahui systemd. Karena systemd menganggap belum perlu membaca semua definisi unit di tampilan ini, systemd hanya menampilkan informasi tentang berkas itu saja. Keluarannya memiliki dua kolom: berkas unit dan keadaan.

      Output

      UNIT FILE STATE proc-sys-fs-binfmt_misc.automount static dev-hugepages.mount static dev-mqueue.mount static proc-fs-nfsd.mount static proc-sys-fs-binfmt_misc.mount static sys-fs-fuse-connections.mount static sys-kernel-config.mount static sys-kernel-debug.mount static tmp.mount static var-lib-nfs-rpc_pipefs.mount static org.cups.cupsd.path enabled . . .

      Keadaan biasanya berupa enabled, disabled, static, atau masked. Dalam konteks ini, static berarti berkas unit tidak berisi bagian install, yang digunakan untuk mengaktifkan unit. Dengan demikian, unit-unit ini tidak dapat diaktifkan. Biasanya, ini berarti unit melakukan tindakan sekali-jalan atau hanya digunakan sebagai dependensi unit lain dan tidak boleh dijalankan dengan sendirinya.

      Kita akan membahas makna masked sebentar lagi.

      Manajemen Unit

      Sejauh ini, kita telah menggunakan beberapa layanan dan menampilkan informasi tentang unit dan berkas unit yang diketahui oleh systemd. Namun, kita dapat mengetahui informasi yang lebih spesifik tentang unit menggunakan beberapa perintah tambahan.

      Menampilkan Berkas Unit

      Untuk menampilkan berkas unit yang telah dimuat systemd ke dalam sistemnya, Anda dapat menggunakan perintah cat (ini telah ditambahkan dalam systemd versi 209). Misalnya, untuk melihat berkas unit daemon penjadwalan atd, kita dapat mengetikkan:

      • systemctl cat atd.service

      Output

      [Unit] Description=ATD daemon [Service] Type=forking ExecStart=/usr/bin/atd [Install] WantedBy=multi-user.target

      Keluaran adalah berkas unit yang diketahui systemd sebagai proses yang sedang berjalan. Ini dapat menjadi hal penting jika Anda baru-baru ini telah memodifikasi berkas unit atau jika Anda mengesampingkan beberapa opsi tertentu dalam fragmen berkas unit (kita akan membahasnya nanti).

      Menampilkan Dependensi

      Untuk melihat pohon dependensi unit, Anda dapat menggunakan perintah list-dependencies:

      • systemctl list-dependencies sshd.service

      Perintah ini akan menampilkan pemetaan hierarki yang harus ditangani agar dapat memulai unit tersebut. Dependensi dalam konteks ini meliputi unit-unit yang diperlukan oleh atau yang diinginkan oleh unit di atasnya.

      Output

      sshd.service ├─system.slice └─basic.target ├─microcode.service ├─rhel-autorelabel-mark.service ├─rhel-autorelabel.service ├─rhel-configure.service ├─rhel-dmesg.service ├─rhel-loadmodules.service ├─paths.target ├─slices.target . . .

      Dependensi rekursif hanya ditampilkan untuk unit .target, yang menandakan keadaan sistem. Untuk menampilkan daftar semua dependensi secara rekursif, sertakan bendera --all.

      Untuk menampilkan dependensi terbalik (unit yang bergantung pada unit yang ditentukan), Anda dapat menambahkan bendera --reverse pada perintah. Bendera lain yang berguna adalah --before dan --after, yang dapat digunakan untuk menampilkan unit yang bergantung pada unit yang ditentukan yang masing-masing dimulai sebelum dan setelah unit itu sendiri.

      Memeriksa Properti Unit

      Untuk melihat properti tingkat rendah dari suatu unit, Anda dapat menggunakan perintah show. Perintah ini akan menampilkan daftar properti yang diatur untuk unit yang ditentukan menggunakan format key=value:

      • systemctl show sshd.service

      Output

      Id=sshd.service Names=sshd.service Requires=basic.target Wants=system.slice WantedBy=multi-user.target Conflicts=shutdown.target Before=shutdown.target multi-user.target After=syslog.target network.target auditd.service systemd-journald.socket basic.target system.slice Description=OpenSSH server daemon . . .

      Jika ingin menampilkan properti tunggal, Anda dapat memberikan bendera -p bersama nama properti. Misalnya, untuk melihat konflik yang dimiliki unit sshd.service, Anda dapat mengetikkan:

      • systemctl show sshd.service -p Conflicts

      Output

      Conflicts=shutdown.target

      Melakukan Masking dan Unmasking Unit

      Di bagian manajemen layanan, kita telah melihat cara menghentikan atau menonaktifkan layanan, tetapi systemd juga memiliki kemampuan untuk menandai suatu unit menjadi tidak dapat dimulai sama sekali, secara otomatis atau manual, dengan menautkannya ke /dev/null. Perintah ini disebut masking unit, dan dapat dilakukan dengan perintah mask:

      • sudo systemctl mask nginx.service

      Perintah ini akan mencegah layanan Nginx dimulai, secara otomatis atau manual, selama unit tersebut diberi mask.

      Jika Anda memeriksa list-unit-files, Anda akan melihat layanan kini tercantum sebagai diberi mask:

      • systemctl list-unit-files

      Output

      . . . kmod-static-nodes.service static ldconfig.service static mandb.service static messagebus.service static nginx.service masked quotaon.service static rc-local.service static rdisc.service disabled rescue.service static . . .

      Jika Anda berupaya memulai layanan, Anda akan melihat pesan seperti ini:

      • sudo systemctl start nginx.service

      Output

      Failed to start nginx.service: Unit nginx.service is masked.

      Untuk melakukan unmask di suatu unit, agar unit dapat digunakan lagi, gunakan perintah unmask:

      • sudo systemctl unmask nginx.service

      Ini akan mengembalikan unit ke keadaan sebelumnya, yang memungkinkannya dimulai atau diaktifkan.

      Mengedit Berkas Unit

      Walaupun format spesifik untuk berkas unit berada di luar lingkup tutorial ini, systemctl memberikan mekanisme bawaan untuk mengedit dan memodifikasi berkas unit jika Anda perlu membuat penyesuaian. Fungsionalitas ini ditambahkan dalam systemd versi 218.

      Perintah edit secara asali akan membuka cuplikan berkas unit untuk unit tersebut:

      • sudo systemctl edit nginx.service

      Ini akan berupa berkas kosong yang dapat digunakan untuk mengesampingkan atau menambahkan arahan ke definisi unit. Direktori akan dibuat dalam direktori /etc/systemd/system yang berisi nama unit dengan tambahan .d. Misalnya, untuk nginx.service, suatu direktori bernama nginx.service.d akan dibuat.

      Di dalam direktori ini, cuplikan akan dibuat dengan nama override.conf. Bila unit dimuat, systemd dalam memori akan menggabungkan cuplikan yang dikesampingkan dengan berkas unit penuh. Arahan cuplikan akan menjadi prioritas daripada yang ada dalam berkas unit asli.

      Jika Anda ingin mengedit berkas unit penuh alih-alih membuat cuplikan, Anda dapat memberikan bendera --full:

      • sudo systemctl edit --full nginx.service

      Perintah ini akan memuat berkas unit saat ini ke dalam editor, yang dapat dimodifikasi. Ketika keluar dari editor, berkas yang diubah ditulis ke /etc/systemd/system, yang akan menjad prioritas dari definisi unit sistem (biasanya ditemukan di /lib/systemd/system).

      Untuk menghapus tambahan yang telah Anda buat, hapus direktori konfigurasi .d unit atau berkas layanan yang dimodifikasi dari /etc/systemd/system. Misalnya, untuk menghapus cuplikan, kita dapat mengetikkan:

      • sudo rm -r /etc/systemd/system/nginx.service.d

      Untuk menghapus berkas unit yang dimodifikasi sepenuhnya, kita ketikkan:

      • sudo rm /etc/systemd/system/nginx.service

      Setelah menghapus berkas atau direktori, Anda harus memuat ulang proses systemd agar tidak lagi berupaya merujuk berkas-berkas ini dan kembali menggunakan salinan sistem. Anda dapat melakukannya dengan mengetikkan:

      • sudo systemctl daemon-reload

      Menyesuaikan Keadaan Sistem (Runlevel) dengan Target

      Target adalah berkas unit khusus yang menggambarkan keadaan sistem atau titik sinkronisasi. Seperti unit lainnya, berkas yang mendefinisikan target dapat diidentifikasi melalui akhirannya, yang dalam hal ini adalah .target. Target tidak mencocokkan dirinya sendiri, melainkan digunakan untuk mengelompokkan unit lain menjadi satu.

      Perintah ini dapat digunakan untuk membawa sistem ke keadaan tertentu, seperti sistem init lainnya yang menggunakan runlevel. Semua itu digunakan sebagai referensi ketika fungsi tertentu tersedia, yang memungkinkan Anda menentukan keadaan yang diinginkan sebagai ganti unit individual yang diperlukan untuk menghasilkan keadaan itu.

      Misalnya, ada swap.target yang digunakan untuk menunjukkan bahwa swap siap digunakan. Unit yang menjadi bagian dari proses ini dapat menyinkronkan dengan target ini dengan menunjukkannya dalam konfigurasi bahwa unit tersebut WantedBy= atau RequiredBy= oleh swap.target. Unit yang mengharuskan swap tersedia dapat menentukan syarat ini menggunakan spesifikasi Wants=, Requires=, dan After= untuk menandakan sifat hubungannya.

      Mendapatkan dan Mengatur Target Asali

      Proses systemd memiliki target asali yang digunakannya saat melakukan boot sistem. Memenuhi kaskade dependensi dari target tunggal itu akan membawa sistem ke keadaan yang diinginkan. Untuk menemukan target asali bagi sistem Anda, ketikkan:

      Output

      multi-user.target

      Jika ingin menetapkan target asali yang berbeda, Anda dapat menggunakan set-default. Misalnya, jika Anda telah menginstal desktop grafis dan ingin agar sistem melakukan boot ke desktop grafis secara asali, Anda dapat mengubah target asalinya:

      • sudo systemctl set-default graphical.target

      Menampilkan Daftar Target yang Tersedia

      Anda bisa mendapatkan daftar target yang tersedia di sistem dengan mengetikkan:

      • systemctl list-unit-files --type=target

      Tidak seperti runlevel, beberapa target dapat aktif sekaligus. Target aktif menandakan bahwa systemd berupaya memulai semua unit yang terikat ke target dan tidak mencoba untuk memutusnya lagi. Untuk melihat semua target aktif, ketikkan:

      • systemctl list-units --type=target

      Mengisolasi Target

      Bisa saja memulai semua unit yang telah dikaitkan dengan target dan menghentikan semua unit yang bukan bagian dari pohon dependensi. Perintah yang kita perlukan untuk melakukannya disebut isolate. Ini mirip dengan mengubah runlevel di sistem init lainnya.

      Misalnya, jika Anda beroperasi di lingkungan grafis dengan graphical.target aktif, Anda dapat mematikan sistem grafis dan memasukkan sistem ke bentuk baris perintah multipengguna dengan mengisolasi multi-user.target. Karena graphical.target bergantung pada multi-user.target, tetapi tidak ada cara lainnya lagi, semua unit grafis akan dihentikan.

      Anda mungkin perlu melihat dependensi target yang diisolasi sebelum melakukan prosedur ini untuk memastikan bahwa Anda tidak menghentikan layanan penting:

      • systemctl list-dependencies multi-user.target

      Bila Anda puas dengan unit yang akan dibiarkan tetap aktif, Anda dapat mengisolasi target dengan mengetikkan:

      • sudo systemctl isolate multi-user.target

      Menggunakan Pintasan untuk Kejadian Penting

      Ada beberapa target yang didefinisikan untuk kejadian penting seperti mematikan daya atau melakukan boot ulang. Namun, systemctl juga memiliki beberapa pintasan yang memberikan beberapa fungsi tambahan.

      Misalnya, untuk menempatkan sistem ke dalam mode pertolongan (pengguna tunggal), Anda dapat menggunakan perintah rescue sebagai ganti isolate rescue.target:

      Perintah ini akan memberikan fungsi tambahan yang memperingatkan semua pengguna yang log masuk tentang kejadian tersebut.

      Untuk menghentikan sistem, Anda dapat menggunakan perintah halt:

      Untuk mulai mematikan daya sepenuhnya, Anda dapat menggunakan perintah poweroff:

      Menyalakan ulang dapat dimulai dengan perintah reboot:

      Ini semua akan memperingatkan para pengguna yang log masuk mengenai kejadian tersebut, satu-satunya hal yang tidak akan dilakukan oleh menjalankan atau mengisolasi target. Harap diperhatikan bahwa kebanyakan mesin akan menautkan perintah yang lebih pendek dan lebih konvensional untuk operasi ini agar berfungsi secara benar dengan systemd.

      Misalnya, untuk melakukan boot ulang sistem, Anda biasanya dapat mengetikkan:

      Kesimpulan

      Saat ini, Anda sudah memahami beberapa kemampuan dasar dari perintah systemctl yang memungkinkan Anda berinteraksi dengan dan mengendalikan instans systemd. Utilitas systemctl adalah titik utama interaksi Anda untuk manajemen layanan dan keadaan sistem.

      Walaupun systemctl terutama beroperasi dengan proses inti systemd, ada beberapa komponen lain di ekosistem systemd yang dikendalikan oleh utilitas lain. Kemampuan lainnya, seperti manajemen log dan sesi pengguna yang ditangani oleh daemon terpisah dan utilitas manajemen (masing-masing yaitu journald/journalctl dan logind/loginctl). Menyisihkan waktu untuk memahami berbagai alat dan daemon lain akan membuat manajemen menjadi tugas yang lebih mudah.



      Source link

      How To Sandbox Processes With Systemd On Ubuntu 20.04


      The author selected the Free and Open Source Fund to receive a donation as part of the Write for DOnations program.

      Introduction

      Sandboxing is a computer security technique that focuses on isolating a program or process from parts of a system that it does not need to interact with during normal operation. When a new program is started it has all of the abilities of the user that it runs as. These abilities are very often much more than the program needs to perform its function. This can lead to security issues when a bad actor manipulates the program to access some of its unused abilities to do something the program would not normally do.

      The purpose of sandboxing is to identify exactly what abilities and resources a program needs, and then block off everything else.

      The system management suite of tools systemd is used on almost all major Linux distributions to start, stop, and manage programs and processes. It has many sandboxing options that restrict how the process it starts accesses the host system, making it more secure.

      The aim of this tutorial is not to create the strictest sandbox environment possible, but rather to use the recommended and easily enabled settings to make your system more secure.

      In this tutorial you will run through a practical demonstration of how to use systemd’s sandboxing techniques on Ubuntu 20.04 for an efficient workflow to implement and to test these techniques. Any process that runs on a Linux system that uses systemd can be made more secure with these techniques.

      Prerequisites

      You will need the following to begin this guide:

      Step 1 — Installing lighttpd

      In this tutorial, we will sandbox the lighttpd web server. lighttpd was not chosen because it is any less secure than other software, but because it is a small program with a single function that is easily sandboxed. This makes it an excellent choice for a learning application.

      Let’s update the system to start:

      Check the packages that will be upgraded on your system before typing y:

      Then install lighttpd:

      • sudo apt install lighttpd

      This installation process will automatically install and enable a systemd service file for lighttpd. This will make lighttpd start on a system reboot.

      Now that we have lighttpd installed and running on our system we’ll get familiar with the systemd tools we will use when we start sandboxing.

      Step 2 — Preparing Your System

      In this step, you will get familiar with the systemd commands that you will use and prepare your system to enable you to efficiently sandbox a process.

      systemd is an umbrella name for a suite of tools that each have different names. The two that you will use are systemctl and journalctl. systemctl manages processes and their service files, while journalctl interacts with the system log.

      systemd uses service files to define how a process will be managed. systemd loads these files from several locations in the file system. The following command will show you the location of the active service file and display any overrides that are in use:

      • sudo systemctl cat process.service

      You need to replace process with the process that you are working on. Here lighttpd is used:

      • sudo systemctl cat lighttpd.service

      This is the output from the previous command:

      Output

      # /lib/systemd/system/lighttpd.service [Unit] Description=Lighttpd Daemon After=network-online.target [Service] Type=simple PIDFile=/run/lighttpd.pid ExecStartPre=/usr/sbin/lighttpd -tt -f /etc/lighttpd/lighttpd.conf ExecStart=/usr/sbin/lighttpd -D -f /etc/lighttpd/lighttpd.conf ExecReload=/bin/kill -USR1 $MAINPID Restart=on-failure [Install] WantedBy=multi-user.target

      This output shows that the service file is located at /lib/systemd/system/lighttpd.service and that there are no override options in use. Override options add to or modify the base service file. You will use overrides to sandbox lighttpd with a dedicated override file.

      Override files are located at /etc/systemd/system/process.service.d/override.conf. systemd has a dedicated edit command that will create an override file at the correct location and run systemctl daemon-reload after saving and exiting the editor. The systemctl daemon-reload instructs systemd to use any new configuration you wrote.

      The systemd edit command has the following form:

      • sudo systemctl edit process.service

      When you run this command systemd will usually choose your default CLI editor, but this is not always the case and you may find yourself in vi or even ed. You can configure which editor systemd will use by setting the SYSTEMD_EDITOR shell variable.

      Set this shell variable by adding a line to your ~/.bashrc file. Open this file with a text editor:

      And add the following line:

      ~/.bashrc

      export SYSTEMD_EDITOR=editor
      

      Change editor to your preferred CLI editor. Here is the line set to use the nano editor:

      ~/.bashrc

      export SYSTEMD_EDITOR=nano
      

      Confirm that this is set after you log out and log in again with the echo command:

      This command will print the name of the editor you set.

      The SYSTEMD_EDITOR shell variable is only set in your user’s shell and not root’s shell that gets opened by sudo. To pass this variable to root’s shell invoke systemctl edit using sudo -E:

      • sudo -E systemctl edit process.service

      The final recommendation will make debugging your sandboxing easier by showing you any errors that your changes have caused. These errors will be recorded by the system log, which is accessed with the journalctl command.

      During your sandboxing, you will make many changes that break the process you are trying to sandbox. For that reason, it is a good idea to open a second terminal and dedicate it to following the system log. This will save time re-opening the system log.

      Follow the system log in the second terminal by running:

      • sudo journalctl -f -u process.service
      • -f: Follow or tail the system log so new lines are displayed immediately.
      • -u process.service: Only show the log lines for the process you are sandboxing.

      The following is what you need to run to print only lighttpd’s errors:

      • sudo journalctl -f -u lighttpd.service

      Next you’ll begin editing the override.conf file and start sandboxing lighttpd.

      Step 3 — Enforcing a User and Group

      In this step, you will set the non-root user that lighttpd will run as.

      In its default configuration, lighttpd starts running as the root user and then changes to the www-data user and group. This is a problem because while lighttpd is running as root it can do anything that root can do—which is anything.

      systemd provides the ability to start and run the process as a non-root user thereby avoiding this problem.

      Return to your first terminal session and begin editing the override file by running:

      • sudo -E systemctl edit lighttpd.service

      Now, add the following lines:

      lighttpd override file

      [Service]
      User=www-data
      Group=www-data
      
      • [Service]: Tells systemd that the following options should be applied to the [Service] section.
      • User=www-data: Defines the user to start the process as.
      • Group=www-data: Defines the group to start the process as.

      Next, save and exit the editor and restart lighttpd with the following command:

      • sudo systemctl restart lighttpd.service

      lighttpd will not be able to start because it was using the root authority to write a PID file to a location owned by root. The www-data user is not able to write to directories owned by root. This problem is indicated in the system log that will appear in your second terminal session:

      journalctl error message

      Aug 29 11:37:35 systemd lighttpd[7097]: 2020-08-29 11:37:35: (server.c.1233) opening pid-file failed: /run/lighttpd.pid Permission denied

      Resolving this issue follows the process of sandboxing which is:

      1. Implement a sandbox restriction.
      2. Restart the process and check for errors.
      3. Fix any errors.

      Next you’ll resolve the PID file issue while still enforcing the user and group restrictions you set in this section.

      Step 4 — Managing the PID File

      A PID file is a file that contains the PID or Process Identification Number of a running process. Long-running programs like lighttpd use them to manage their own processes. The problem that you encountered in the previous section was that lighttpd was unable to write its PID file to /run/lighttpd.pid, because /run/ is owned by root.

      systemd has the RuntimeDirectory option for this problem, which you will use to give lighttpd a location that it can write its PID file to.

      The RuntimeDirectory option allows you to specify a directory under /run/ that will be created with the user and group you set in Step 3 when systemd starts lighttpd. lighttpd will be able to write its PID into this directory without needing root’s authority.

      First, open and edit the override file with the same command that you used in Step 3:

      • sudo -E systemctl edit lighttpd.service

      Next, add the following line under the two lines that you already added to the override file:

      lighttpd override file

      RuntimeDirectory=lighttpd
      

      Save and exit the editor.

      You do not add the full path to the directory with the RuntimeDirectory, only the name of the directory under /run/. In this case, the directory that systemd will create is /run/lighttpd/.

      You now need to configure lighttpd to write its PID file into the new directory /run/lighttpd/ instead of /run/.

      Open lighttpd’s configuration file with a text editor:

      • sudo nano /etc/lighttpd/lighttpd.conf

      Change the following line:

      /etc/lighttpd/lighttpd.conf

      server.pid-file             = "/run/lighttpd.pid"
      

      To:

      /etc/lighttpd/lighttpd.conf

      server.pid-file             = "/run/lighttpd/lighttpd.pid"
      

      Save and exit the editor.

      Now, restart lighttpd:

      • sudo systemctl restart lighttpd.service

      It won’t start because it is unable to do something that needs one of root’s capabilities. Next you’ll resolve this new issue.

      Step 5 — Borrowing root’s Capabilities

      The following line in the system log explains the issue that stopped lighttpd starting:

      journalctl error message

      Aug 29 12:07:22 systemd lighttpd[7220]: 2020-08-29 12:07:22: (network.c.311) can't bind to socket: 0.0.0.0:80 Permission denied

      Only root can open a network port below number 1024. lighttpd is trying to open the HTTP port 80, but it is being denied because the www-data user cannot do that.

      The issue is resolved by giving the lighttpd process a small part of root’s power—that is, to open ports below 1024.

      root’s “power” is divided into abilities called “capabilities”. The root user has every capability and can therefore do anything. Breaking root’s power up into capabilities means that they can be given individually to non-root processes. This allows that process to do something that would have required a full root user, but a normal user can now do with one of root’s capabilities.

      The systemd option to give a process one or more of root’s capabilities is the AmbientCapabilities option.

      Open the override file:

      • sudo -E systemctl edit lighttpd.service

      Then add the following line under the lines you already added:

      lighttpd override file

      AmbientCapabilities=CAP_NET_BIND_SERVICE
      

      The CAP_NET_BIND_SERVICE capability allows a process to open ports under 1024.

      Save and exit the file.

      lighttpd will now be able to start.

      You now have a working lighttpd web server that you have made more secure than its default configuration. There are more sandboxing options provided by systemd that you can use to make your target process even more secure. We will explore some of these in the following sections.

      In the next step, you will restrict what lighttpd can access in the file system.

      Step 6 — Locking Down the Filesystem

      The lighttpd process runs as the www-data user and so can access any file on the system that www-data has permission to read and write to. In the case of www-data that isn’t very much, but still more than lighttpd needs.

      The first and easiest sandbox setting is the ProtectHome option. This option stops the process from reading or writing to anything under /home/. lighttpd does not need access to anything under /home/ so implementing this will protect all of your private files without affecting lighttpd.

      Open the override file:

      • sudo -E systemctl edit lighttpd.service

      Then add the following line at the bottom of the file:

      lighttpd override file

      ProtectHome=true
      

      Save and exit the editor then restart lighttpd to check that it is working as you expect with the following command:

      • sudo systemctl restart lighttpd.service

      You have protected /home/, but that still leaves the rest of the file system. This is taken care of with the ProtectSystem option, which stops a process from writing to parts of the file system.

      The ProtectSystem option has three settings that offer increasing levels of protection. They are as follows:

      • true: Sets the following directories to read only:
      • full: Sets the following directories to read only:
      • strict: Sets the following directories to read only:

      A higher level of protection is more secure so set the ProtectSystem option to strict by adding the following line to the override file:

      lighttpd override file

      ProtectSystem=strict
      

      Save and exit the editor and restart lighttpd with the following command:

      • sudo systemctl restart lighttpd.service

      lighttpd will not be able to start because it needs to write its log files to /var/log/lighttpd/ and the strict setting forbids that. The following line in the system log shows the problem:

      journalctl error message

      Aug 29 12:44:41 systemd lighttpd[7417]: 2020-08-29 12:44:41: (server.c.752) opening errorlog '/var/log/lighttpd/error.log' failed: Read-only file system

      This issue was anticipated by systemd with the LogsDirectory option. It takes the name of a directory under /var/log/ that the process is permitted to write its logs into.

      Open the override file again in your first terminal session:

      • sudo -E systemctl edit lighttpd.service

      The lighttpd log directory is /var/log/lighttpd/ so add the following line to the bottom of the override file:

      lighttpd override file

      LogsDirectory=lighttpd
      

      Save and exit the editor and restart lighttpd:

      • sudo systemctl restart lighttpd.service

      lighttpd will now be able to start and run.

      Note: If you are sandboxing a process other than lighttpd and want to allow your process to write access to a specific directory outside of /var/log/ use the ReadWritePaths option.

      In the next step, you will limit how the lighttpd process can interact with the rest of the system by restricting the system calls it is allowed to make.

      Step 7 — Restricting System Calls

      A system call is how a program requests something from the kernel. The number of system calls is quite large and includes actions like reading, writing, and deleting files, hardware related tasks like mounting a file system, spawning process, rebooting, and many more.

      systemd has created groups of system calls that processes, like lighttpd, typically use and which exclude calls that they do not. The blocked system calls are things like mounting a file system and rebooting the system, which lighttpd never needs to do.

      First, open the override file:

      • sudo -E systemctl edit lighttpd.service

      Add the following line to the bottom of the file to use the SystemCallFilter option to set the @system-service group:

      lighttpd override file

      SystemCallFilter=@system-service
      

      Save and exit the editor and restart lighttpd:

      • sudo systemctl restart lighttpd.service

      In the next section, you will apply the remaining recommended sandboxing options.

      Step 8 — Implementing Further Options

      The systemd documentation recommends the following options are enabled for long-running, networked processes like lighttpd. These settings are all optional, but each one makes the process you are sandboxing more secure and should be used if you can.

      You should enable these options one at a time and restart your process after each one. If you add them all at once debugging a problem will be much harder.

      The recommended options following are accompanied by a brief description of what they do. Add these lines to your override file under the lines you have already added:

      lighttpd override file

      NoNewPrivileges=true
      

      This option stops the sandboxed process and any of its children from obtaining new privileges.

      lighttpd override file

      ProtectKernelTunables=true
      

      This option stops the process from changing any kernel variables.

      lighttpd override file

      ProtectKernelModules=true
      

      This option stops the process from loading or unloading kernel modules.

      lighttpd override file

      ProtectKernelLogs=true
      

      This option stops the process from reading and writing directly to the kernel log. It must use the system log application to record any log messages.

      lighttpd override file

      ProtectControlGroups=true
      

      This option stops the process from modifying the system control groups.

      lighttpd override file

      MemoryDenyWriteExecute=true
      

      This option stops the process from modifying any code that is running in the system’s memory.

      lighttpd override file

      RestrictSUIDSGID=true
      

      This option stops the process from setting the set-user-ID (SUID) or set-group-ID (SGID) on files or directories. This ability can be abused to elevate privileges.

      lighttpd override file

      KeyringMode=private
      

      This option stops the process from accessing the kernel keyring of other processes that are running as the same user.

      lighttpd override file

      ProtectClock=true
      

      This option stops the process from changing the hardware and software system clocks.

      lighttpd override file

      RestrictRealtime=true
      

      This option stops the process from enabling real-time scheduling that can be abused to overload the CPU.

      lighttpd override file

      PrivateDevices=true
      

      This option stops the process from accessing physical devices attached to the system such as storage devices or USB devices.

      lighttpd override file

      PrivateTmp=true
      

      This option forces the process to use private /tmp/ and /var/tmp/ directories. This stops the process from being able to read other program’s temporary files that are stored in those shared system directories.

      lighttpd override file

      ProtectHostname=true
      

      This option stops the process from changing the system’s hostname.

      The process that you have sandboxed is now much more secure than it was in its default configuration. You can now take these techniques and use them for any other processes you need to secure on your Linux system.

      Conclusion

      In this article, you made the lighttpd program more secure by using the systemd sandboxing options. You can use these techniques with any process that systemd manages allowing you to continue to improve the security of your system.

      The entire list of sandboxing and other security options are found in systemd’s online documenation. Also, check out further security topics on the DigitalOcean Community.



      Source link

      What is systemd?


      Updated by Linode

      Contributed by

      Linode


      Use promo code DOCS10 for $10 credit on a new account.

      systemd is a Linux initialization system and service manager that includes features like on-demand starting of daemons, mount and automount point maintenance, snapshot support, and processes tracking using Linux control groups. systemd provides a logging daemon and other tools and utilities to help with common system administration tasks.

      Lennart Poettering and Kay Sievers wrote systemd, inspired by macOS’s launchd and Upstart, with the goal of creating a modern and dynamic system. Notably, systemd provides aggressive parallelization capabilities and dependency-based service control logic, allowing for services to start in parallel and leading to a quicker boot time. These two aspects were present in Upstart, but improved upon by systemd.

      systemd is the default init system for the major Linux distributions but is backwards compatible with SysV init scripts. SysVinit is an initialization system which predates systemd and uses a simplified approach to service startup. systemd not only manages system initialization, but also provides alternatives for other well known utilities, like cron and syslog. Because systemd does several things within the Linux user space, many have criticized it for violating the Unix philosophy, which emphasizes simplicity and modularity.

      This guide provides an introduction to systemd by taking a closer look at systemd units. The Mount Units section will analyze a unit file that is shipped by default with systemd on an Ubuntu 18.04 system, while the Timer Units section will create a custom unit file on the same system.

      Note

      All examples in this guide were created with a Linode running Ubuntu 18.04.

      The Linux Boot Process and systemd

      To better understand what is meant by an initialization system, this section provides a high-level overview of the Linux boot process.

      Linux requires an initialization system during its boot and startup process. At the end of the boot process, the Linux kernel loads systemd and passes control over to it and the startup process begins. During this step, the kernel initializes the first user space process, the systemd init process with process ID 1, and then goes idle unless called again. systemd prepares the user space and brings the Linux host into an operational state by starting all other processes on the system.

      Below is a simplified overview of the entire Linux boot and startup process:

      1. The system powers up.
        1 The BIOS does minimal hardware initialization and hands over control to the boot loader.
      2. The boot loader calls the kernel.
      3. The kernel loads an initial RAM disk that loads the system drives and then looks for the root file system.
      4. Once the kernel is set up, it begins the systemd initialization system.
      5. systemd takes over and continues to mount the host’s file systems and start services.

      systemd Units

      systemd introduces the concept of systemd units and there are several types, such as a service unit, mount unit, socket unit and slice unit. Units are defined in unit configuration files, which include information about the unit type and its behavior.

      Expand the note below for a comprehensive list of all available systemd unit types.


      systemd Unit Types

      Unit TypeFile ExtensionDescription
      Service unit.serviceA system service.
      Target unit.targetA group of systemd units.
      Automount unit.automountA file system automount point.
      Device unit.deviceA device file recognized by the kernel.
      Mount unit.mountA file system mount point.
      Path unit.pathA file or directory in a file system.
      Scope unit.scopeAn externally created process.
      Slice unit.sliceA group of hierarchically organized units that manage system processes.
      Snapshot unit.snapshotA saved state of the systemd manager.
      Socket unit.socketAn inter-process communication socket.
      Swap unit.swapA swap device or a swap file.
      Timer unit.timerA systemd timer.

      For most distributions using systemd, unit files are stored in the following directories:

      • The /usr/lib/systemd/user/ directory is the default location where unit files are installed by packages. Unit files in the default directory should not be altered.
      • The /run/systemd/system/ directory is the runtime location for unit files.
      • The /etc/systemd/system/ directory stores unit files that extend a service. This directory will take precedence over unit files located anywhere else in the system.

      Mount Units

      This section will take a closer look at a mount unit configuration file to provide a better understanding of the structure of systemd unit files. You will also use systemd utilities to discover information about the running Linode mount units.

      A mount unit configuration file contains information about a file system mount point that is controlled and supervised by systemd. To find the existing mount units on your Linode, use the systemctl tool to view a complete list:

      systemctl list-units --type=mount
      

      Your output will display each mount unit that is currently active:

      UNIT                          LOAD   ACTIVE SUB     DESCRIPTION
      -.mount                       loaded active mounted Root Mount
      dev-hugepages.mount           loaded active mounted Huge Pages File System
      dev-mqueue.mount              loaded active mounted POSIX Message Queue File System
      proc-sys-fs-binfmt_misc.mount loaded active mounted Arbitrary Executable File Formats File S
      run-user-1000.mount           loaded active mounted /run/user/1000
      sys-fs-fuse-connections.mount loaded active mounted FUSE Control File System
      sys-kernel-config.mount       loaded active mounted Kernel Configuration File System
      sys-kernel-debug.mount        loaded active mounted Kernel Debug File System
      var-lib-lxcfs.mount           loaded active mounted /var/lib/lxcfs
      
      LOAD   = Reflects whether the unit definition was properly loaded.
      ACTIVE = The high-level unit activation state, i.e. generalization of SUB.
      SUB    = The low-level unit activation state, values depend on unit type.
      
      9 loaded units listed. Pass --all to see loaded but inactive units, too.
      To show all installed unit files use 'systemctl list-unit-files'.
      

      To view information about a specific mount unit, use the systemctl status command with the unit’s name:

      systemctl status sys-fs-fuse-connections.mount
      

      Systemctl will provide information that resembles the example output. This example displays a single entry for the FUSE Control File System mount point:

      ● sys-fs-fuse-connections.mount - FUSE Control File System
      Loaded: loaded (/lib/systemd/system/sys-fs-fuse-connections.mount; static; vendor preset: enabled)
      Active: active (mounted) since Wed 2018-08-29 18:34:43 UTC; 21h ago
          Where: /sys/fs/fuse/connections
          What: fusectl
          Docs: https://www.kernel.org/doc/Documentation/filesystems/fuse.txt
              https://www.freedesktop.org/wiki/Software/systemd/APIFileSystems
          Tasks: 0 (limit: 2320)
      CGroup: /system.slice/sys-fs-fuse-connections.mount
      

      The systemctl output provides the location of the mount unit configuration file, along with information on the state of the mount, location of the mount, links to documentation, running tasks, and its corresponding CGroup. Many of these details are defined in the mount unit’s configuration file.

      FUSE is a file system framework that provides an interface for user space programs to export a virtual file system to the Linux kernel. It can also be used to provide data access with a file system directory structure and file operations to any object.

      Inspect the contents of the FUSE control file system’s mount unit configuration file with systemctl:

      systemctl cat sys-fs-fuse-connections.mount
      

      You will see a similar output:

      [Unit]
      Description=FUSE Control File System
      Documentation=https://www.kernel.org/doc/Documentation/filesystems/fuse.txt
      Documentation=https://www.freedesktop.org/wiki/Software/systemd/APIFileSystems
      DefaultDependencies=no
      ConditionPathExists=/sys/fs/fuse/connections
      ConditionCapability=CAP_SYS_ADMIN
      ConditionVirtualization=!private-users
      After=systemd-modules-load.service
      Before=sysinit.target
      
      [Mount]
      What=fusectl
      Where=/sys/fs/fuse/connections
      Type=fusectl
      

      All unit files must contain a [Unit] section that outlines generalized options, dependencies and conditions for the unit. The example mount unit file contains some of the following options:

      • There are no service dependencies for this mount unit, indicated by DefaultDependencies=no. However, ConditionPathExists denotes that the directory /sys/fs/fuse/connections must exist before the mount unit is started. This condition is necessary, since under the FUSE control file system each connection will have it’s own directory in this location.
      • The name of a mount unit file must correspond to the mount point directories it controls, which is why this particular mount unit configuration file is named sys-fs-fuse-connections.mount.

      A mount unit file must contain a [Mount] section. The example mount unit file has the following options:

      • The What option, which can be a partition name, path or UUID to mount.
      • The Where option declares an absolute path to a mount point. If the mount point does not exist, it will be created.
      • The Type option denotes the file system type.

      Note

      The official systemd manual notes that configuring mount points through /etc/fstab is the recommended approach. systemd has a system-fstab-generator that translates the information in the fstab file into systemd mount and swap units at runtime.

      There are many other unit file types available in systemd. Read the Use systemd to Start a Linux Service at Boot guide to become more familiar with the service unit type.

      Timer Units

      You can use systemd timer unit files to automate tasks, similarly to how cron jobs are used. However, with timer units you will also have access to systemd’s powerful logging capabilities.

      To better understand systemd timer units, this section will outline how a timer unit can be used to create periodic backups for a mysql database.

      You will need three separate files:

      • A script that will execute and create a backup for a MySQL database located in the /usr/local/bin/ directory.
      • A service unit file, that will handle running the script.
      • A timer unit file, which will define when and how often the service will initialize.

      Note

      Your script, service unit file, and timer unit file should all have 644 read and write permissions.

      Below is the script that creates a backup .sql file named for a database named testdb. The script will append a date and timestamp to the file name:

      /usr/local/bin/my-db-backup.sh
      1
      2
      3
      4
      
      #!/bin/sh
      
      stamp=$(date "+%y-%m-%d-%H-%M")
      /usr/bin/mysqldump testdb > ~/backups/my-db-backup-${stamp}.sql

      To bypass being prompted for a MySQL username and password, create a .my.cnf file in your home directory with your MySQL credentials.

      ~/.my.cnf
      1
      2
      3
      
      [mysqldump]
      user=mysqluser
      password=mypassword

      The service unit file is located in the /etc/systemd/system/ directory and contains the following information:

      /etc/systemd/system/my-db-backup.service
      1
      2
      3
      4
      5
      6
      
      [Unit]
      Description=A script to backup mysql database named testdb
      
      [Service]
      # The location of the mysql backup script
      ExecStart=/usr/local/bin/my-db-backup.sh

      The timer unit file is located in the same directory as the service unit file with the same name, but with the .timer extension instead. The unit file contains the following options:

      /etc/systemd/system/my-db-backup.timer
       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      
      [Unit]
      Description=Runs my-db-backup.sh every hour
      
      [Timer]
      # Amount of time to wait after booting before the service runs for the first time
      OnBootSec=10min
      # The time between running each consecutive timer
      OnUnitActiveSec=1h
      # Name of the service file that will be called
      Unit=my-db-backup.service
      
      [Install]
      # Defines which service triggers the custom service on boot
      WantedBy=multi-user.target

      When creating unit files, you can verify the correctness of the file with the following systemd command:

      systemd-analyze verify /etc/systemd/system/my-db-backup.timer
      

      systemd’s system-analyze command provide several other useful analyze and debug options. View the official documentation for more options.

      When you enable the timer, systemd will hook the timer unit into the specified places and ensure it starts on boot. Enable the timer unit with following command:

      systemctl start my-db-backup.timer
      

      When you start the timer unit, systemd will start it right away. To do this, issue the following command:

      systemctl enable my-db-backup.timer
      

      systemd makes common system administration tasks easier to manage with its systemctl and journalctl commands. systemctl can be used to gather detailed information about the overall state of your server and any individual unit type. It can stop and start the server and modify the system state. In the Timer Unit Files section systemctl is used to enable and start an individual timer unit. systemd can be used in a similar way for any unit.

      Read our Introduction to systemctl guide for a deeper dive into this systemd tool.

      systemd’s journalctl tool provides a centralized process and system logging tool. This command allows you to query the systemd journal, which creates and maintains indexed journals from logging information that is pooled from different areas within the system; areas like standard output and standard error of service units, log messages via syslog, and kernel log messages. In this way, system administrators can use a single tool to monitor and debug a server.

      To learn some commonly used journalctl commands, see our guide Use journalctl to View Your System’s Logs.

      More Information

      You may wish to consult the following resources for additional information on this topic. While these are provided in the hope that they will be useful, please note that we cannot vouch for the accuracy or timeliness of externally hosted materials.

      Join our Community

      Find answers, ask questions, and help others.

      This guide is published under a CC BY-ND 4.0 license.



      Source link