Search code examples
ubuntuenvironment-variablessystemdsystemctl

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.


Solution

  • 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