[Blog](https://deploywithox.com/blog) [Guides](https://deploywithox.com/blog#c-guides) # 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. Saurav Sharma Dec 1, 2026 12 min read On this page - [A small service to test with](https://deploywithox.com/blog/systemd-service-environment-variables#heading-demo) - [Why the service does not see your shell's variables](https://deploywithox.com/blog/systemd-service-environment-variables#heading-shell) - [See the environment the process really got](https://deploywithox.com/blog/systemd-service-environment-variables#heading-see) - [Why a changed value does not show up](https://deploywithox.com/blog/systemd-service-environment-variables#heading-change) - [Quotes and % signs in Environment=](https://deploywithox.com/blog/systemd-service-environment-variables#heading-inline) - [What an EnvironmentFile accepts, and what a .env file breaks](https://deploywithox.com/blog/systemd-service-environment-variables#heading-file) - [Using variables in ExecStart](https://deploywithox.com/blog/systemd-service-environment-variables#heading-execstart) - [A missing environment file stops the service](https://deploywithox.com/blog/systemd-service-environment-variables#heading-missing) - [Keep secrets out of Environment= lines](https://deploywithox.com/blog/systemd-service-environment-variables#heading-secrets) - [Remove the demo](https://deploywithox.com/blog/systemd-service-environment-variables#heading-cleanup) - [How ox sets your app's variables](https://deploywithox.com/blog/systemd-service-environment-variables#heading-ox) - [Key takeaways](https://deploywithox.com/blog/systemd-service-environment-variables#key-takeaways) - [Frequently asked questions](https://deploywithox.com/blog/systemd-service-environment-variables#faq) - [Next step](https://deploywithox.com/blog/systemd-service-environment-variables#heading-next) 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 ```bash 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, '')!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 ```bash sudo install -d -m 700 /etc/envdemo sudo install -m 600 /dev/null /etc/envdemo/envdemo.env sudoedit /etc/envdemo/envdemo.env ``` INI ```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 ```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 ```bash sudo systemctl daemon-reload sudo systemctl enable --now envdemo sudo journalctl -u envdemo -o cat -n 4 ``` Code ```text 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](https://www.freedesktop.org/software/systemd/man/latest/systemd.exec.html) 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 ```bash 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 changed | Run | | --- | --- | | The unit file or a drop-in | `sudo 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 ```text 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 ```bash 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 unit | What the process got | | --- | --- | | `Environment=NOQUOTE=a b` | `NOQUOTE=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%off` | `PERCENT=50ubuntuff` | | `Environment=DOUBLEPCT=50%%off` | `DOUBLEPCT=50%off` | | `Environment=PCT40=p%40ss` | nothing; the journal logged "Failed to resolve specifiers in PCT40=p%40ss, ignoring: Invalid slot" | | `Environment=LITERAL=$HOME` | `LITERAL=$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 file | What the process got | | --- | --- | | `UNQUOTED=two words` | `two words`, both spaces kept | | `DOUBLE="double quoted"` | `double quoted` | | `SINGLE='single $HOME'` | `single $HOME` | | `INLINE=value # not a comment` | `value # not a comment` | | `export EXPORTED=1` | nothing; 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 = spaced` | `SPACED=spaced` | | `BACKSLASH=pa\ss\\word` | `pass\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](https://www.freedesktop.org/software/systemd/man/latest/systemd.service.html). With `GREETING=hello world`, this line: INI ```ini ExecStart=/usr/bin/printf "[%%s]\n" $GREETING ${GREETING} $(whoami) ~ ``` printed: Code ```text [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 ```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 ```text 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 ```bash 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 ```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 ```bash 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](https://deploywithox.com/docs/operate/variables) 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](https://deploywithox.com/blog/zero-downtime-deploys-systemd-caddy), and for a whole app set up by hand with these pieces, [deploy Django without Docker](https://deploywithox.com/blog/deploy-django-to-a-vps-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](https://deploywithox.com/docs/quickstart) takes you from a fresh server to a live app, and the [variables docs](https://deploywithox.com/docs/operate/variables) show how ox stores what you set. New to running apps on your own server? [How ox runs your apps](https://deploywithox.com/self-hosting) shows what ox sets up on your server. On this page - [A small service to test with](https://deploywithox.com/blog/systemd-service-environment-variables#heading-demo) - [Why the service does not see your shell's variables](https://deploywithox.com/blog/systemd-service-environment-variables#heading-shell) - [See the environment the process really got](https://deploywithox.com/blog/systemd-service-environment-variables#heading-see) - [Why a changed value does not show up](https://deploywithox.com/blog/systemd-service-environment-variables#heading-change) - [Quotes and % signs in Environment=](https://deploywithox.com/blog/systemd-service-environment-variables#heading-inline) - [What an EnvironmentFile accepts, and what a .env file breaks](https://deploywithox.com/blog/systemd-service-environment-variables#heading-file) - [Using variables in ExecStart](https://deploywithox.com/blog/systemd-service-environment-variables#heading-execstart) - [A missing environment file stops the service](https://deploywithox.com/blog/systemd-service-environment-variables#heading-missing) - [Keep secrets out of Environment= lines](https://deploywithox.com/blog/systemd-service-environment-variables#heading-secrets) - [Remove the demo](https://deploywithox.com/blog/systemd-service-environment-variables#heading-cleanup) - [How ox sets your app's variables](https://deploywithox.com/blog/systemd-service-environment-variables#heading-ox) - [Key takeaways](https://deploywithox.com/blog/systemd-service-environment-variables#key-takeaways) - [Frequently asked questions](https://deploywithox.com/blog/systemd-service-environment-variables#faq) - [Why does my systemd service not see variables from .bashrc?](https://deploywithox.com/blog/systemd-service-environment-variables#heading-faq-bashrc) - [Do I need daemon-reload after changing an EnvironmentFile?](https://deploywithox.com/blog/systemd-service-environment-variables#heading-faq-reload) - [Can systemd read my app's .env file?](https://deploywithox.com/blog/systemd-service-environment-variables#heading-faq-dotenv) - [Next step](https://deploywithox.com/blog/systemd-service-environment-variables#heading-next) Written by Saurav Sharma Builds ox. Writes about running apps on servers you own, without Docker and without a platform bill. [Older post Automate PostgreSQL Backups on a VPS with a systemd Timer](https://deploywithox.com/blog/postgres-backups-on-a-vps) [Newer post Caddy Reverse Proxy 502: Fix dial tcp Connection Refused](https://deploywithox.com/blog/caddy-reverse-proxy-502-connection-refused) ## Keep reading - Guides [PostgreSQL Connection String Password Special Characters](https://deploywithox.com/blog/postgres-connection-string-special-characters) Fix a PostgreSQL connection string whose password has special characters: percent-encode it once, check how libpq reads it, keep it off the command line. Saurav Sharma Dec 3, 2026 16 min read - Guides [Back Up a Live SQLite Database Before Deploy, and Prove It](https://deploywithox.com/blog/sqlite-backup-before-deploy) Back up a live SQLite database before a deploy with .backup or VACUUM INTO, not cp, which can miss WAL commits. Then prove the copy in an empty folder. Saurav Sharma Dec 2, 2026 15 min read - Guides [Strapi Uploads Gone After Redeploy? Restore and Keep Them](https://deploywithox.com/blog/strapi-uploads-disappear-after-redeploy) Recover Strapi uploads that return 404 after a redeploy. Compare files across releases, resolve conflicting copies, and keep uploads in one shared folder. Saurav Sharma Dec 2, 2026 22 min read ## 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](https://deploywithox.com/login/github) [Read the docs](https://deploywithox.com/docs)