Search code examples
node.jscentos7systemd

How do I run a Node.js app as a systemd service?


So I have a node.js app that I am trying to deploy and run as a systemd service.

Here's the .service file:

[Unit]
Description=My app

[Service]
ExecStart=/usr/local/bin/node /var/www/html/schema.js
Restart=always
User=root
Group=nogroup
Environment=PATH=/usr/bin:/usr/local/bin
Environment=NODE_ENV=production
WorkingDirectory=/var/www/html

[Install]
WantedBy=multi-user.target

Unfortunately, it just does not work.... I keep getting an error:

Feb 12 09:56:49 myswerth systemd[1]: Started my-app app.
-- Subject: Unit my-app.service has finished start-up
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
-- 
-- Unit my-app.service has finished starting up.
-- 
-- The start-up result is done.
Feb 12 09:56:49 my-server systemd[23765]: Failed at step GROUP spawning /usr/local/bin/node: No such process
-- Subject: Process /usr/local/bin/node could not be executed
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
-- 
-- The process /usr/local/bin/node could not be executed and failed.
-- 
-- The error number returned by this process is 3.
Feb 12 09:56:49 myswerth systemd[1]: my-app.service: main process exited, code=exited, status=216/GROUP
Feb 12 09:56:49 myswerth systemd[1]: Unit my-app.service entered failed state.
Feb 12 09:56:49 myswerth systemd[1]: my-app.service failed.
Feb 12 09:56:49 myswerth systemd[1]: my-app.service holdoff time over, scheduling restart.
Feb 12 09:56:49 myswerth systemd[1]: Stopped My app app.
-- Subject: Unit my-app.service has finished shutting down
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
-- 
-- Unit my-app.service has finished shutting down.

I'm not really sure why it is kicking up this error. I have tried to access the file manually and can confirm it is located in /usr/local/bin/node and furthermore that I can open node by running it (which I can?) so I have no clue why it cant execute? I have also checked the execute permissions. All user groups can execute so ya.... I'm at a loss here...


Solution

  • Make sure node is in the path by running which node

    Try the following:

    in your schema.js file add the following line at the top

    #!/usr/bin/env node
    

    this will remove the need to specify the node in the ExecStart

    Also make sure to

    chmod +x /var/www/html/schema.js
    

    Additional options worth considering adding to the Service definition:

    PIDFile=/tmp/your-app-name.pid
    KillSignal=SIGQUIT
    WorkingDirectory=/var/www/html/
    

    Try to fix to use:

    Group=root