Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass environment variables to a service started by systemd

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.

like image 303
Nicolas El Khoury Avatar asked Jul 28 '17 13:07

Nicolas El Khoury


People also ask

Where do I put systemd environment files?

Systemd Files and Paths Unit files are stored in the /usr/lib/systemd directory and its subdirectories, while the /etc/systemd/ directory and its subdirectories contain symbolic links to the unit files necessary to the local configuration of the host. We recommend putting your scripts in /etc/systemd/system .

What is EnvironmentFile?

A list of files containing the environment variables to pass to a container. You can specify up to ten environment files. The file must have a . env file extension.

What is ExecStart in systemd?

ExecStartPost= commands are only run after the commands specified in ExecStart= have been invoked successfully, as determined by Type= (i.e. the process has been started for Type=simple or Type=idle , the last ExecStart= process exited successfully for Type=oneshot , the initial process exited successfully for Type= ...


1 Answers

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
like image 97
papey Avatar answered Sep 23 '22 06:09

papey