Skip to main content

πŸš€ How to Create a Service in Ubuntu Using systemd

🎯 Why Do We Create a Service in Ubuntu?​

A service is a background process (daemon) that runs continuously, even after logging out or rebooting the system.

βœ… Key Benefits of Creating a Service:​

  • πŸ— Automation & Startup Execution β†’ Ensures apps start automatically on boot.
  • πŸ”„ Process Management & Stability β†’ Monitors and restarts failed applications.
  • πŸ” Security & User Permissions β†’ Runs services with restricted users.
  • βš™οΈ Standardized Control β†’ Uses systemctl for easy management.

πŸ›  Step-by-Step Guide to Creating a Service in Ubuntu​

πŸ“Œ Step 1: Prepare Your Script or Application​

Before creating a service, ensure you have a script or application ready. For example, a simple bash script /opt/myapp/start.sh:

#!/bin/bash
echo "My service is running..."
while true; do
sleep 60
done

Give it execution permissions:

chmod +x /opt/myapp/start.sh

πŸ“Œ Step 2: Create a systemd Service File​

Create a new service file in /etc/systemd/system/:

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

πŸ”Ή Add the following content:

[Unit]
Description=My Custom Application Service
After=network.target

[Service]
ExecStart=/opt/myapp/start.sh
WorkingDirectory=/opt/myapp
Restart=always
User=root
Group=root

[Install]
WantedBy=multi-user.target

πŸ” Explanation:

  • [Unit] β†’ Defines metadata & dependencies.
  • [Service] β†’ Configures execution & restart behavior.
    • User=root β†’ Runs the service as the root user. This means the service has full system privileges, which is not recommended for security-sensitive applications. Consider running under a non-root user if possible.
    • Group=root β†’ Defines the group under which the service runs. Keeping it root means the service has administrative group access.
  • [Install] β†’ Enables auto-start at boot.

πŸ“Œ Step 3: Reload systemd & Start the Service​

After creating the service file, reload systemd:

sudo systemctl daemon-reload

Start your service:

sudo systemctl start myapp

Check if it's running:

sudo systemctl status myapp

πŸ“Œ Step 4: Enable the Service to Start on Boot​

To ensure the service starts automatically:

sudo systemctl enable myapp

Disable auto-start (if needed):

sudo systemctl disable myapp

πŸ“Œ Step 5: Managing the Service​

ActionCommand
βœ… Startsudo systemctl start myapp
β›” Stopsudo systemctl stop myapp
πŸ”„ Restartsudo systemctl restart myapp
πŸ”Ž Check Statussudo systemctl status myapp
πŸ”₯ Check if Activesudo systemctl is-active myapp
πŸš€ Check if Enabled at Bootsudo systemctl is-enabled myapp

πŸ“Œ Step 6: View Logs of the Service​

View historical logs:

sudo journalctl -u myapp --no-pager

πŸ“‘ Real-time logs:

sudo journalctl -u myapp -f

πŸ“Œ Step 7: Remove the Service​

To remove the service: 1️⃣ Stop & disable it:

sudo systemctl stop myapp
sudo systemctl disable myapp

2️⃣ Delete the service file:

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

3️⃣ Reload systemd:

sudo systemctl daemon-reload

4️⃣ (Optional) Remove script:

sudo rm -r /opt/myapp

πŸš€ Alternative Methods to Run Applications Without Creating a Service

1️⃣ Running in the Foreground (Basic Execution)​

node /home/ubuntu/app.js

❌ Stops when the terminal is closed.


2️⃣ Using nohup (Ignore Hangups)​

nohup node /home/ubuntu/app.js > output.log 2>&1 &

βœ… Keeps running after logout. ❌ No auto-restart if crashed.


3️⃣ Using screen (Persistent Sessions)​

screen -S myapp
node /home/ubuntu/app.js

πŸ”Ή Press Ctrl + A, then D to detach. πŸ”Ή Reattach with:

screen -r myapp

❌ Stops on reboot.


4️⃣ Using tmux (Better Alternative to Screen)​

tmux new -s myapp
node /home/ubuntu/app.js

πŸ”Ή Detach with Ctrl + B, then D. πŸ”Ή Reattach with:

tmux attach -t myapp

❌ Doesn’t persist after reboot.


5️⃣ Using supervisor (Process Monitoring & Auto-Restart)​

πŸ”Ή Install supervisor:

sudo apt update && sudo apt install supervisor -y

πŸ”Ή Create a configuration file:

sudo nano /etc/supervisor/conf.d/myapp.conf

πŸ”Ή Add the following content:

[program:myapp]
command=/usr/bin/node /home/ubuntu/app.js
autostart=true
autorestart=true
stderr_logfile=/var/log/myapp.err.log
stdout_logfile=/var/log/myapp.out.log

πŸ”Ή Apply changes and start the process:

sudo supervisorctl reread
sudo supervisorctl update
sudo supervisorctl start myapp

βœ… Auto-restarts if the process crashes!


πŸ†š Comparison: systemd vs. Other Methods

MethodProsCons
πŸ† systemd serviceBest for production, auto-start, loggingRequires root access
πŸ›  nohup & &Simple, keeps runningNo auto-restart, hard to track
πŸ”„ screen/tmuxKeeps running in a sessionStops after reboot
πŸ“Š SupervisorAuto-restart, loggingExtra installation required

🎯 Final Thoughts​

βœ… If you need a long-running, auto-managed process, use systemd services. βœ… If you need something temporary, nohup or screen/tmux are fine. βœ… If you need process monitoring, supervisor is a great option.

For DevOps & production environments, systemd services are the best choice! πŸš€πŸ”₯


πŸ’‘ **Let me know if you need further clarifications!**😊