Skip to main content

Run an application as a service in Linux

This is using PM2 to setup the background service We are running the service as the root user so we don't run into run permission issue.

This can be configured to:

  1. Run on the system bootup
  2. Automatically restart after a crash after a set amount of seconds

Setting up the background service

  1. We have to have a working application executible with permissions to execute. Eg: app with execution permissions

    If the application don't have the right permissions, provide them by:

    sudo chmod +x <file_name>
  2. Note the working directory which the app has to be executed from.

  3. Switch to root user.

    sudo su
  4. Create and open the following file with sudo permissions to write. Should change the name socket_app to your application name.

    sudo nano /etc/systemd/system/socket_app.service
  5. Add the following content to the file. Change the content according to your application and requirement.

    [Unit]
    Description=Socket Server for the Sensor Mesh Network

    [Service]
    WorkingDirectory=/home/pavan/git/gqc/linux_socket_app
    ExecStart=/home/pavan/git/gqc/linux_socket_app/build/socket_app
    Restart=on-failure
    # Restart service after 2 seconds if the service crashes:
    RestartSec=10
    SyslogIdentifier=socket_app
    User=root

    [Install]
    WantedBy=default.target
  6. Add the service

    sudo systemctl enable socket_app.service
    sudo systemctl start socket_app.service
  7. Check the status of the service

    sudo systemctl status socket_app.service

    status

Monitoring the output of the service

If you want to monitor the screen output of the service:

sudo journalctl -fu socket_app.service