13

I have a nodeJS service built using NodeJs. This service requires some environment variables to be passed to it. Moreover, I created a systemd unit file to start it from systemctl. For some weird reasons, the service, when started with systemctl, does not read the environment variables. For instance, one environment variable is the HOST, which contains the IP to which the sails app will be binded. However, if I start the service with sails lift or node app.js, it does read the environment variables. Here is the unit file:

[Unit]
Description=project

[Service]
ExecStart=/usr/bin/node /mnt/project/app.js
Restart=always
StandardOutput=syslog

[Install]
WantedBy=multi-user.target

I tried everything. I added the environment variables to /etc/environment and pointed the unit file to it, I also added them to the unit file, but nothing worked.

Nicolas El Khoury
  • 5,867
  • 4
  • 18
  • 28

2 Answers2

27

Something like

[Unit]
Description=project

[Service]
ExecStart=/usr/bin/node /mnt/project/app.js
Restart=always
StandardOutput=syslog
Environment=KEY=VALUE

[Install]
WantedBy=multi-user.target

https://coreos.com/os/docs/latest/using-environment-variables-in-systemd-units.html

Or, an alternative like :

EnvironmentFile=/path/to/env

With format :

KEY=VALUE
KEY2=VALUE

EDIT :

For multiple env values

[Unit]
Description=project

[Service]
ExecStart=/usr/bin/node /mnt/project/app.js
Restart=always
StandardOutput=syslog
Environment=KEY=VALUE
Environment=KEY2=VALUE2 KEY3=VALUE3


[Install]
WantedBy=multi-user.target
rogerdpack
  • 62,887
  • 36
  • 269
  • 388
papey
  • 3,854
  • 1
  • 19
  • 18
0

You could wrap your startup command as a shell-script

startup.sh

#!/bin/sh
NODE_ENV='PRODUCTION' node server.js

And then execute the shell script in your system service.

[Unit]
Description=MyNodeServer
After=mysql.service
StartLimitIntervalSec=0
[Service]
User=www-data
Group=www-data
WorkingDirectory=/var/www/html/mynodeserver
Type=simple
PIDFile=/run/mynodeserver.pid
ExecStart=/usr/bin/sh /absolute/path/to/startup.sh
StandardOutput=file:/var/www/html/mynodeserver/stdout.txt
StandardError=file:/var/www/html/mynodeserver/stderr.txt
KillMode=process

Restart=always
RestartSec=1

[Install]
WantedBy=default.target