How to Handle Environment Variables and Secrets on a Host

Handling environment variables and secrets on a host means keeping configuration out of your code and out of your web root, injecting it at runtime through the process environment or a protected file that only your application user can read. The goal is that the same code runs in development, staging and production with different values, and that no key ever ends up in a git commit, a public directory, or a log line.

This article walks through the mechanics of environment variables secrets hosting: how variables actually reach a process, where to put them, how to keep them out of version control and backups, and how to rotate them when something goes wrong. It assumes you have shell access to the server and can edit files as the user that runs your application.

How variables actually reach your application

An environment variable is just a string in the environment block that the kernel hands to a process when it is created with execve. A child process inherits a copy of its parent's environment. That single fact explains almost every behaviour you will see: variables set in your interactive SSH session are not automatically visible to a PHP-FPM pool, a systemd unit, or a process started by a different supervisor, because those daemons were started from a different parent with a different environment.

So the question is never "did I export the variable" but "which process is the parent of my application, and how does that parent get its environment". For a systemd service the answer is a unit file and an EnvironmentFile= directive. For PHP-FPM it is env[...] entries in the pool configuration, or clear_env = no plus the environment of the master process. For a Node or Python app behind a process manager, it is whatever wrapper starts it. Check what your app actually sees rather than assuming:

$ sudo systemctl show myapp.service -p Environment -p EnvironmentFiles
Environment=APP_ENV=production
EnvironmentFiles=/etc/myapp/myapp.env (ignore_errors=no)

That output tells you exactly which files systemd reads and in what order. If the variable you expected is missing, the fix is almost always in that unit file, not in your shell profile.

Where to store environment variables secrets on hosting

Pick a location outside the document root and outside any directory your application serves. A common pattern on Linux is /etc/<appname>/<appname>.env, owned by root with mode 0640 and group ownership set to the application's group. The application user can read it; nobody else can. If your app must run as an unprivileged user and the file is in /etc, that is fine as long as the group is right.

$ sudo install -o root -g myapp -m 0640 /dev/null /etc/myapp/myapp.env
$ sudo -u myapp test -r /etc/myapp/myapp.env && echo readable
readable
$ sudo -u nobody test -r /etc/myapp/myapp.env || echo denied
denied

The install command creates the file with the right owner and mode in one step, which is less error prone than creating it and then remembering to chmod. The two test calls verify that the application user can read it and an unrelated user cannot. Run those checks after every change to permissions, because a recursive chmod or a deployment script that copies files can quietly widen them.

The file format matters less than the discipline around it. A plain KEY=value file works with systemd's EnvironmentFile= and with most application frameworks, which parse it themselves. Quote values that contain spaces or shell metacharacters, and do not rely on shell expansion inside the file, because systemd does not perform it the way a shell would. If a value contains a literal $, escape it as $$ in a systemd environment file.

Keeping secrets out of code, logs and backups

Add the file to .gitignore and, more importantly, commit a template with placeholder names so a new developer knows which keys are required without ever seeing real values. Name it something like .env.example and make the values obviously fake. A secret that appears in a git history is compromised even if you delete the file later, because the object stays in the repository until it is garbage collected and every clone already has it.

Logs are the other common leak. Frameworks that dump the request environment on an unhandled exception will print your API keys to a log file that may be world readable or shipped to an external service. Configure your error handler to redact known key names, and check what an error page actually renders before you put the app in front of users. The same applies to debug endpoints and health checks that echo configuration.

Backups deserve a mention because they are easy to forget. If your backup job archives the application directory, and you stored the env file inside it, the secrets are now in an archive that may be copied off the host with weaker permissions than the original. Keep the file outside the backed-up tree, or encrypt the backup and treat the backup credentials with the same care as the secrets themselves.

Rotating and verifying without downtime

When a key needs to change, the safe sequence is: write the new value to the environment file, reload the service so the process re-reads it, then confirm the new value is live before revoking the old one at the provider. A reload is preferable to a restart for most process managers because it keeps connections open, but only if your application actually re-reads configuration on reload. Many do not, and a full restart is the honest choice.

$ sudo systemctl reload myapp.service
$ sudo systemctl show myapp.service -p MainPID
MainPID=4821
$ sudo tr '\0' '\n' < /proc/4821/environ | grep '^APP_ENV='
APP_ENV=production

Reading /proc/<pid>/environ shows the environment the running process actually has, not what the file says. That distinction catches the classic mistake of editing the file and forgetting to reload. The tr converts the null separators into newlines so grep can work line by line. If the PID changes after a reload, the process was restarted rather than reloaded, which is worth knowing.

Finally, make the check part of your deploy. A short post-deploy step that asserts the expected variables are present and non-empty will fail the deploy loudly instead of letting the app start with a missing key and throw confusing errors at the first request. Keep the assertion to names and presence, never print the values.

What to do next

Audit one application this week. List every configuration value it needs, mark which are secret, and confirm each one is read from a file outside the web root with permissions you have verified using test -r as the application user. Move anything that fails that check, add the placeholder template to version control, and add the post-deploy presence check. Once one app is clean, the pattern is easy to repeat across the rest of the host.

Related articles

Subscribe to our newsletter

Get the latest hosting tips, performance insights, and industry news.