BlogGuides

systemd Service Environment Variables, and Why They Fail

Set environment variables in a systemd service with Environment= or EnvironmentFile=, and fix the usual faults: quotes, % signs, a .env file, no restart.

On this page

A systemd service does not see the variables you export in your shell or put in ~/.bashrc. Set them in the unit with Environment= lines or an EnvironmentFile=, run systemctl daemon-reload if you changed the unit, and restart the service, because a running process never picks up a new value. When a variable still looks wrong, it is nearly always one of a few rules about quotes, % signs and the file format, and this post goes through each one. I ran every block here on a fresh Ubuntu 26.04 server with systemd 259.

I build ox, which writes these files for the apps it deploys. You need no ox for any of this, and the end says what ox does for you.

A small service to test with

It helps to have a service that prints what it was given. This Python script prints four variables and then waits:

Shell
sudo install -d /opt/envdemo
sudo tee /opt/envdemo/app.py > /dev/null <<'EOF'
import os, signal

for key in ("APP_ENV", "GREETING", "DATABASE_URL", "SECRET_KEY"):
    print(f"{key}={os.environ.get(key, '<not set>')!r}", flush=True)
signal.pause()
EOF
sudo useradd --system --no-create-home --shell /usr/sbin/nologin envdemo

Make a file for the values that should stay private. Use made-up values while you follow along, because this demo prints them to the journal. Only root can read the file, and the service can still use it, because systemd reads the file as root before it starts your program as another user:

Shell
sudo install -d -m 700 /etc/envdemo
sudo install -m 600 /dev/null /etc/envdemo/envdemo.env
sudoedit /etc/envdemo/envdemo.env
INI
# /etc/envdemo/envdemo.env, owned by root, mode 600
DATABASE_URL=postgres://envdemo:change-me@localhost/envdemo
SECRET_KEY="a value with spaces"

Then the unit, with two values set inline and the rest from the file. Save it as /etc/systemd/system/envdemo.service, for example with sudoedit:

INI
# /etc/systemd/system/envdemo.service
[Unit]
Description=Environment variable demo

[Service]
User=envdemo
Environment=APP_ENV=production
Environment="GREETING=hello world"
EnvironmentFile=/etc/envdemo/envdemo.env
ExecStart=/usr/bin/python3 /opt/envdemo/app.py
Restart=on-failure

[Install]
WantedBy=multi-user.target
Shell
sudo systemctl daemon-reload
sudo systemctl enable --now envdemo
sudo journalctl -u envdemo -o cat -n 4
Code
APP_ENV='production'
GREETING='hello world'
DATABASE_URL='postgres://envdemo:change-me@localhost/envdemo'
SECRET_KEY='a value with spaces'

If you see only a "Started" line, the app had not printed yet, so run the journalctl line again. The quotes around a value with spaces in the file are gone in the value, as they should be. The rest of this post changes one thing at a time in this setup.

Why the service does not see your shell's variables

systemd starts a system service from PID 1, not from your login shell, so export, ~/.bashrc and ~/.profile never reach it. On the test server, a variable added to /etc/environment did not reach it either. PAM reads that file when a session opens, for a login, sudo or a cron job, and a plain service opens no such session. The systemd.exec manual says services start "with just a few environment variables", such as PATH, LANG, USER and HOME. Anything else your app needs has to be written into the unit or its file.

See the environment the process really got

systemctl show envdemo -p Environment looks like the answer, but it lists only the Environment= lines. Values from an EnvironmentFile= do not appear there. Add -p EnvironmentFiles and you get the path of the file, never what is in it. To see what the running process actually has, read it from /proc:

Shell
sudo cat /proc/"$(systemctl show -p MainPID --value envdemo)"/environ | tr '\0' '\n'

That prints every variable, from both sources, as the program sees it. It needs the service to be running. A stopped service has MainPID 0, and the command fails. On a real service it prints every secret to your screen, so add | grep '^NAME=' for the one you want.

Why a changed value does not show up

A process gets its environment once, when it starts. What you need to do after a change depends on what you changed:

You changedRun
The unit file or a drop-insudo systemctl daemon-reload, then sudo systemctl restart envdemo
Only the EnvironmentFile=sudo systemctl restart envdemo

When I changed APP_ENV in the unit and restarted without a reload, the restart succeeded and the process still had the old value. systemd prints a warning on the restart, which is easy to scroll past:

Code
Warning: The unit file, source configuration file or drop-ins of envdemo.service changed on disk. Run 'systemctl daemon-reload' to reload units.

The environment file is different. systemd reads it fresh each time the service starts, so a restart alone was enough, and the running process kept the old value until then.

To change a value without touching the original unit, put it in a drop-in. sudo systemctl edit envdemo opens an editor on /etc/systemd/system/envdemo.service.d/override.conf and reloads when you save. From a script, --stdin does the same without an editor:

Shell
sudo systemctl edit --stdin envdemo <<'EOF'
[Service]
Environment=APP_ENV=staging
EOF
sudo systemctl restart envdemo

A later Environment= line overrides an earlier one with the same name, so the drop-in wins over the unit. systemctl cat envdemo shows the unit and every drop-in in the order they apply, and sudo systemctl revert envdemo removes the drop-ins again.

Quotes and % signs in Environment=

Each Environment= line is split into words, and each word must be a whole NAME=value. The manual's advice for a value with a space is to "put quotes around the whole assignment". Here is what each form gave on the test server:

Line in the unitWhat the process got
Environment=NOQUOTE=a bNOQUOTE=a, and the journal logged "Invalid environment assignment, ignoring: b"
Environment="WHOLE=a b"WHOLE=a b
Environment=MIDDLE="a b"MIDDLE=a b
Environment=PERCENT=50%offPERCENT=50ubuntuff
Environment=DOUBLEPCT=50%%offDOUBLEPCT=50%off
Environment=PCT40=p%40ssnothing; the journal logged "Failed to resolve specifiers in PCT40=p%40ss, ignoring: Invalid slot"
Environment=LITERAL=$HOMELITERAL=$HOME

The % rows are the ones that bite. A unit file treats % followed by a letter as a specifier, so %o became the operating system's ID, ubuntu, and the start went ahead with no warning. A password with % before a letter systemd knows gets changed the same way. A URL-encoded value fares worse: %40, an encoded @, is not a specifier systemd accepts, so it dropped the whole variable and left one line in the journal. Write %% for a literal percent sign in a unit, or keep such values in the environment file, where FILEPCT=50%off arrived unchanged. The last row shows the other side: $ means nothing in Environment=, so one variable cannot be built from another there.

What an EnvironmentFile accepts, and what a .env file breaks

An environment file looks like a shell script but is not run by a shell. These are the lines I added to the test file, and the values the process got:

Line in the fileWhat the process got
UNQUOTED=two wordstwo words, both spaces kept
DOUBLE="double quoted"double quoted
SINGLE='single $HOME'single $HOME
INLINE=value # not a commentvalue # not a comment
export EXPORTED=1nothing; the journal logged "Ignoring invalid environment assignment 'export EXPORTED=1'"
REF=${APP_ENV}-x${APP_ENV}-x, not expanded
DOLLAR=$HOME$HOME, not expanded
SPACED = spacedSPACED=spaced
BACKSLASH=pa\ss\\wordpass\word, each single backslash gone
ESCAPED="tab\there"tab\there, a backslash and a t, not a tab

So a .env file written for a shell or a dotenv library can go wrong in three places. An export line is dropped, with only a line in the journal to say so. A ${OTHER} reference arrives as literal text, and so does a $ in a password. A trailing # comment becomes part of the value. A comment works only on a line of its own that starts with # or ;.

The rules, as the manual states them: an unquoted value keeps its inner spaces, loses the spaces around it, and loses each backslash, which only protects the character after it. A single-quoted value is taken exactly as written, and a double-quoted value treats a backslash as an escape only before ", \, ` and $. Lines without an = are ignored. If you want one format that works in both places, write plain NAME=value lines, double-quote any value with a space, quote, backslash, # or $ in it, and put a backslash before each ", \, ` and $ inside the quotes.

When the same name is set in both places, the file wins: the test unit said APP_ENV=staging, the file said APP_ENV=from-the-file, and the process got the file's value. With several EnvironmentFile= lines, a later file overrides an earlier one.

Using variables in ExecStart

ExecStart= is not run by a shell either. systemd does its own simple substitution, described in the systemd.service manual. With GREETING=hello world, this line:

INI
ExecStart=/usr/bin/printf "[%%s]\n" $GREETING ${GREETING} $(whoami) ~

printed:

Code
[hello]
[world]
[hello world]
[~]

A bare $GREETING is split at spaces into two arguments, and ${GREETING} stays one argument, so use the braces for any value that might hold a space. The $(whoami) argument is gone, because there is no command substitution. systemd read it as a variable with a name it does not accept, put nothing in its place, and left one line in the journal: "Invalid environment variable name evaluates to an empty string: (whoami)". ~ stayed a literal tilde. Note the %% in the format string, for the same reason as above. If you need pipes, $(...) or a default value, run a shell on purpose, and let it read the variables at run time:

INI
ExecStart=/bin/sh -c 'echo "$GREETING from $(whoami)"'

In a unit with User=envdemo that printed hello world from envdemo, and with no User= line, hello world from root. For a long-running app, put exec before the last command inside the quotes, so your program replaces the shell and becomes the main process, the one whose exit systemd watches.

A missing environment file stops the service

When I moved the file away, the restart failed, and the journal named the cause:

Code
envdemo.service: Failed to load environment files: No such file or directory
envdemo.service: Failed with result 'resources'.

A path written as EnvironmentFile=-/etc/envdemo/envdemo.env, with a leading -, makes the file optional, and the service started without its values. Use that only for a file that really is optional. For secrets, a loud failure is better than an app that starts with no database password. Note also that $HOME is not expanded in the path, so write the full path. The %h specifier does not help in a system service: with User=envdemo set, EnvironmentFile=%h/.env still pointed at /root/.env.

Keep secrets out of Environment= lines

Any user on the server can read a unit's Environment= lines. On the test server, an ordinary user with no sudo ran systemctl show envdemo -p Environment and got back APP_ENV and GREETING, and could read the same over D-Bus. The same user got "Permission denied" for the root-only environment file and for the process's /proc/PID/environ. So a password belongs in the file with mode 600, never inline in the unit, which is world-readable too.

The manual goes further and says environment variables "are not suitable for passing secrets", because they are passed down to every child process the app starts. Its answer is LoadCredential=, which hands the service a file in a private folder instead of a variable:

Shell
sudo install -m 600 /dev/null /etc/envdemo/secret_key
sudoedit /etc/envdemo/secret_key
sudo systemctl edit --stdin --drop-in=credential.conf envdemo <<'EOF'
[Service]
LoadCredential=secret_key:/etc/envdemo/secret_key
EOF
sudo systemctl restart envdemo

The service finds the folder in $CREDENTIALS_DIRECTORY, here /run/credentials/envdemo.service, and reads the file from there:

Python
import os
from pathlib import Path

secret = (Path(os.environ["CREDENTIALS_DIRECTORY"]) / "secret_key").read_text().strip()

The ordinary user could not read that file either. The catch is that your app has to read a file, while most frameworks and libraries expect a variable such as DATABASE_URL. For many small apps, a root-only environment file is the trade they make.

Remove the demo

Shell
sudo systemctl revert envdemo
sudo systemctl disable --now envdemo
sudo rm -r /etc/systemd/system/envdemo.service /etc/envdemo /opt/envdemo
sudo systemctl daemon-reload
sudo userdel envdemo

revert deletes the drop-ins made with systemctl edit, so nothing is left in envdemo.service.d.

How ox sets your app's variables

ox runs each app as a plain systemd service, much like the one above, with no Docker. You set a variable on the project's Variables tab, or with ox vars set shop STRIPE_KEY, which asks for the value so it never lands in your shell history. ox writes your values to an environment file only root can read, quoting and escaping each value that needs it by the rules above, and the app's unit loads it with EnvironmentFile=. Saving redeploys the app unless you choose to deploy later, so a new value goes live without a reload or restart to remember, and secret values of six characters or more are hidden in the logs. Your values never go in an Environment= line, so another user on the server cannot list them with systemctl show. ox passes them as variables, not as credentials, so the manual's warning about child processes still applies.

The variables docs cover the rest, including ${NAME} references, which ox fills in at deploy time because systemd will not. For how ox starts the new release next to the old one, see zero-downtime deploys with systemd and Caddy, and for a whole app set up by hand with these pieces, deploy Django without Docker.

Key takeaways

  • A plain system service never sees your shell's variables or /etc/environment. Put them in the unit or an EnvironmentFile=.
  • Changed the unit: daemon-reload, then restart. Changed only the file: restart.
  • Quote the whole assignment in Environment=, and write %% for a percent sign, or %o becomes ubuntu and %40 drops the variable.
  • An environment file drops export lines and does not expand ${OTHER} or $. A trailing comment becomes part of the value.
  • Read /proc/PID/environ to see what the process really has. systemctl show lists only the inline lines.
  • Keep secrets in a root-only file with mode 600, or use LoadCredential=, never in an Environment= line.

Frequently asked questions

Why does my systemd service not see variables from .bashrc?

A system service is started by PID 1, not by your login shell, so nothing from .bashrc, .profile or an export in your terminal reaches it. /etc/environment is read by PAM when a session opens, so it does not reach a service either. Write the values into the unit with Environment= or into a file named by EnvironmentFile=, then restart.

Do I need daemon-reload after changing an EnvironmentFile?

No. systemd reads the environment file each time the service starts, so systemctl restart is enough. You need daemon-reload only after editing the unit file or a drop-in, and then a restart as well. Without the reload, the restart succeeds with the old settings and prints a warning that the unit changed on disk.

Can systemd read my app's .env file?

Often, but check three things first. systemd ignores lines that start with export and logs a warning. It does not expand ${OTHER} references or a dollar sign. A comment after a value becomes part of the value. Plain NAME=value lines, with double quotes around values that hold spaces, work in both systemd and most dotenv libraries.

Next step

Run the /proc command from this post against one of your own services and compare what it prints with what you expected. If you would rather not keep these files by hand, the quickstart takes you from a fresh server to a live app, and the variables docs show how ox stores what you set.

New to running apps on your own server? How ox runs your apps shows what ox sets up on your server.

Keep reading

Deploy to a server you own

ox sets up systemd, Caddy and PostgreSQL on your Ubuntu server and deploys on every push. Free for your first project.

Sign up with GitHub Read the docs