Inherit environment variables in systemd Docker container

To answer the question asked (as it doesn't seem to be answered anywhere else)

"How do I expose environment variables passed to /sbin/init to applications started by it?"

requires some slightly irritating bash, and an extremely useful function of the linux /proc filesystem:

# Import our environment variables from systemd
for e in $(tr "\000" "\n" < /proc/1/environ); do
        eval "export $e"
done

This reads /proc/1/envion, which is the environment given to PID 1, but is delimited by nulls. It uses 'tr' to replace the nulls with new lines, and then iterates over those lines and evals them with a prepended 'export', so they are visible to child processes.

The not-exposing-environment-variables is yet another "feature" of systemd, and they don't consider it a bug.


According to this description, a systemd user instance does not inherit environment variables:

https://wiki.archlinux.org/index.php/Systemd/User#Environment_variables

There is a suggestion here to use oneshot systemd service that configures an EnvironmentFile for the "final" service.

https://stackoverflow.com/questions/25396167/how-do-i-get-etcd-values-into-my-systemd-service-on-coreos