RobStallion
RobStallion

Reputation: 1703

How to use environment variables in a .service script

I have an elixir project on a linux server. I have created a .service script which will start and stop the application with the following commands

systemctl start "my_app".service
systemctl stop "my_app".service

The .service file looks something like this...

[Unit]
Description="example app_name daemon"

[Service]
Type=simple
User=root
Restart=on-failure
Environment=MIX_ENV=prod "PORT=4000"

WorkingDirectory="the file path to my app"

ExecStart=/usr/local/bin/mix phoenix.server

[Install]
WantedBy=multi-user.target

It works as expected, the one exception being that it will not read the environment variables. I can give the application access to them by adding them to the script manually like I have with PORT=4000 above.

I want to know if there is a way for the .service file to access the env vars that I have on my server so I do not have to write them in each I use this script on a new server. Thanks in advance

Feel free to check out the repo if you would like more info on the project! 👍

Upvotes: 3

Views: 2701

Answers (2)

cmtm
cmtm

Reputation: 302

In addition to what iamauser said, which is probably the answer you're looking for, there's another way to modify environment variables of services before they're launched. You can use systemctl's environment commands. Note that this will affect systemd's environment itself and all future services it launches. There are more bad reasons to use this than there are good, so avoid using this if iamauser's solution is sufficient.

Upvotes: 0

iamauser
iamauser

Reputation: 11479

You are looking for EnvironmentFile= directive in [Service] section.

EnvironmentFile=/path/to/some/textFile

Read here for more info.

Upvotes: 6

Related Questions