0

This is the first time I try to create a start-up script for Ubuntu. I need to launch an express server for my API and I have followed Making Node.js service always alive on Ubuntu Server.

So my server.js look like this (I also made a chmod +x on it):

import express from 'express'
import morgan from 'morgan'
import bodyParser from 'body-parser'
import mongoose from 'mongoose'
import router from './router'

// chargement du fichier .env qui contient les différentes configuration du projet
require('dotenv').config({path: __dirname + '/.env'})

// Connexion à MongoDB
mongoose.connect('mongodb://localhost/Lyveat_Rider')

// Initialisation du serveur http
const app = express()

// Logger qui affiche toutes les requêtes dans la console
app.use(morgan('combined'))
// Parseur du body pour les requêtes
app.use(bodyParser.urlencoded({ extended: false }));

// Utilise v1 comme prefix pour l'API
app.use('/v1', router)

// Launch the server on port 3000
const server = app.listen(process.env.PORT, () => {
  const { address, port } = server.address();
  console.log(`Listening at http://${address}:${process.env.PORT}`)
});

I have created a service named server_node.service inside the /etc/systemd/system/ with this content :

[Unit]
Description=Node.js Lyveat_Rider  Http Server

[Service]
PIDFile=/tmp/lyveat_rider-99.pid
Restart=always
KillSignal=SIGQUIT
WorkingDirectory=/home/dev/lyveat/api
ExecStart=/home/dev/lyveat/api/server.js

[Install]
WantedBy=multi-user.target

and I have try multiple things, first without the header (#!usr/bin/env node) I have this error :

Failed at step EXEC spawning /home/dev/lyveat/api/server.js: Exec format error

After I put the header I have the error :

/usr/bin/env: ‘node /** server.js */\r’: No such file or directory

I also try with nodejs instead of node and I have try this command I found on another subject :

ln -s /usr/bin/nodejs /usr/bin/node

So I really don't how to make it work.

1
  • Your ExecStart is js file. I'm pretty sure you shall specify full path of node server to run it with. I.e /usr/bin/node /.../jsfile.js
    – Vitali Pom
    Feb 5, 2020 at 19:01

1 Answer 1

0

I know this is not the solution for your method of creating a service for it, but this is what I do for my servers.

Try PM2. It can easily run multiple nodejs servers and apps and manage them. It is easy to setup and can start your server on boot and also monitor and start it if it stops for any reason. This quick start tells you what you need.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .