Hướng dẫn tạo service khởi chạy cùng hệ thống trên Linux

・Published on:

Hướng dẫn tạo service khởi động cùng hệ thống bằng systemd (Linux) – cách này áp dụng cho hầu hết distro như Ubuntu, Debian, CentOS, Fedora… 👍


1️⃣ Xác định chương trình cần chạy

Ví dụ:

  • Script: /opt/myapp/start.sh
  • Hoặc binary: /usr/local/bin/myapp

Lưu ý: file phải có quyền thực thi

chmod +x /opt/myapp/start.sh

2️⃣ Tạo file service

Service system nằm trong:

/etc/systemd/system/

Tạo file:

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

3️⃣ Nội dung service mẫu

🔹 Service chạy script đơn giản

[Unit]
Description=My App Service
After=network.target

[Service]
Type=simple
ExecStart=/opt/myapp/start.sh
Restart=always
RestartSec=5
User=root
WorkingDirectory=/opt/myapp

[Install]
WantedBy=multi-user.target

🔹 Nếu là Node / Java / Python app

Ví dụ Node.js:

[Service]
Type=simple
ExecStart=/usr/bin/node /opt/myapp/index.js

Hoặc Python:

ExecStart=/usr/bin/python3 /opt/myapp/main.py

4️⃣ Reload systemd & enable service

sudo systemctl daemon-reexec
sudo systemctl daemon-reload
sudo systemctl enable myapp.service

👉 enable = tự động chạy khi boot


5️⃣ Start / kiểm tra service

sudo systemctl start myapp.service
sudo systemctl status myapp.service

Xem log:

journalctl -u myapp.service -f

6️⃣ Các tuỳ chọn hay dùng

Tuỳ chọnÝ nghĩa
Restart=alwaysTự restart khi crash
Restart=on-failureRestart khi exit code ≠ 0
After=network.targetĐợi network lên
User=abcChạy bằng user cụ thể
Environment=KEY=valueSet biến môi trường

Ví dụ env:

Environment=NODE_ENV=production
Environment=PORT=3000

7️⃣ Gỡ service (nếu cần)

sudo systemctl disable myapp.service
sudo systemctl stop myapp.service
sudo rm /etc/systemd/system/myapp.service
sudo systemctl daemon-reload