如何在Linux服务器的.service脚本中读取环境变量(Elixir项目)
Hey there! I’ve dealt with this exact scenario when deploying Elixir apps with systemd—hardcoding environment variables in the .service file gets messy fast, so let’s go through the reliable ways to make your service pick up pre-configured variables from your server.
1. Load a system-wide or custom environment file
Systemd lets you directly import variables from a file using the EnvironmentFile directive. This is great if you already have variables stored in a standard file like /etc/environment, or if you want to keep all your app’s variables in a dedicated file.
For example, if your variables live in /opt/my_elixir_app/env_vars (formatted as KEY=VALUE on each line), update your .service file’s [Service] section:
[Service] # Load variables from your custom file EnvironmentFile=/opt/my_elixir_app/env_vars ExecStart=/path/to/your/elixir/start_script Restart=always
If you want to pull in system-wide variables from /etc/environment, just replace the path with that file.
⚠️ Important: The file path must be absolute, and the file should have strict permissions (e.g., chmod 600 /opt/my_elixir_app/env_vars) to prevent unauthorized access.
2. Launch your app via a login shell to load shell configs
If your variables are defined in shell config files like /etc/profile or ~/.profile, systemd won’t load these by default because it doesn’t run a shell. To fix this, wrap your app start command in a bash login shell:
[Service] # The -lc flag makes bash act as a login shell, loading system/user profile files ExecStart=/bin/bash -lc 'exec /path/to/your/elixir/start_script' Restart=always
The exec command replaces the bash process with your Elixir app, so you don’t leave an extra shell running in the background.
3. Import individual variables explicitly
If you only need a handful of specific variables from the system environment, you can use the Environment directive to reference them. Note that systemd doesn’t expand shell variables natively, so this works best if the variable is already set in systemd’s context (e.g., via /etc/environment):
[Service] # Pull PORT from the system environment Environment="PORT=${PORT}" ExecStart=/path/to/your/elixir/start_script Restart=always
After making changes
Don’t forget to reload systemd’s configuration and restart your service for changes to take effect:
sudo systemctl daemon-reload sudo systemctl restart your_elixir_app.service
To verify the variables are being loaded, run:
systemctl show your_elixir_app.service --property=Environment
Or fire up your Elixir app’s IEx shell and run System.get_env("PORT") to confirm the variable is accessible.
内容的提问来源于stack exchange,提问作者RobStallion

