Server Setup - spospordo/espresso-api GitHub Wiki

Running server.js as a service

install node.js

sudo apt update
sudo apt install -y nodejs npm

Clone repository

clone the project into the directory of your choosing. /home/pi or /home/ works great.

git clone https://github.com/spospordo/espresso-api.git 

Install dependencies

npm install

Create the Service File:

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

sudo nano /etc/systemd/system/espresso-api.service

Edit the Service File:

Add the following content to the file, replacing yourusername with your username and my-node-app with your app name: (your username could be 'pi'>

[Unit]
Description=My Node.js App
After=network.target

[Service]
ExecStart=/usr/bin/node /home/<yourusername>/espresso-api/server.js
WorkingDirectory=/home/<yourusername>/espresso-api
Restart=always
User=pi
Group=pi
Environment=PATH=/usr/bin:/usr/local/bin
Environment=NODE_ENV=production
KillMode=process
RestartSec=10

[Install]
WantedBy=multi-user.target

Explanation

Explanation of the service file:

ExecStart: This is the command to start your application. Replace /home/pi/my-node-app/server.js with the path to your server.js file.
WorkingDirectory: This is the directory where your app is located.
Restart=always: This makes sure that the service is restarted automatically if it crashes.
User=pi: This specifies the user under which the service will run. Replace pi with your username if it’s different.
Environment=NODE_ENV=production: This sets the environment variable NODE_ENV to production. You can change this to development if needed.

Reload the systemd Configuration

After creating the service file, reload the systemd configuration to make the system aware of your new service.

sudo systemctl daemon-reload

Start the Service

Now, start the service with the following command:

sudo systemctl start espresso-api

Enable the Service to Start on Boot

If you want the service to start automatically whenever the Raspberry Pi boots up, run the following command:

sudo systemctl enable espresso-api

Check the Service Status

To ensure the service is running correctly, check its status:

sudo systemctl status espresso-api

Logs for the Service

To view the logs of your Node.js app, use journalctl:

sudo journalctl -u espresso-api

Other Commands:

sudo systemctl stop espresso-api
sudo systemctl restart espresso-api
⚠️ **GitHub.com Fallback** ⚠️