« Back to Systemd: Frequently Asked Questions

How to set environment variables in a systemd unit?

How to set environment variables in a systemd unit?

Define Environment or EnvironmentFile in the systemd unit to set the environment variable directly or have it retrieved from a file.

Systemd units can use environment variables and forward them to an application. To set an enviroment variable, use the Environment or EnvironmentFile option.

Define Environment

The basic option to set an environment variable is using Environment followed by the variable name and value.

[Service]
Environment="MYVAR=hello world"

This defines the variable MYVAR with the value ‘hello world’

Define EnvironmentFile

Environment variables can also be stored within a file by using the option EnvironmentFile. This option might be very useful for automatic deployments, especially if a service unit is used within different environments (such as DEV and PROD). The systemd unit can remain the same, while the file containing the variables needs to be filled with the correct variables and values.

[Service]
EnvironmentFile=/data/env/MYAPP

When using a file to store the environment variables, use the format “VAR=VALUE” (without quotes)

Other questions related to Systemd

    Related articles

    Like to learn more? Here is a list of articles within the same category or having similar tags.

    Feedback

    Small picture of Michael Boelen

    This article has been written by our Linux security expert Michael Boelen. With focus on creating high-quality articles and relevant examples, he wants to improve the field of Linux security. No more web full of copy-pasted blog posts.

    Discovered outdated information or have a question? Share your thoughts. Thanks for your contribution!

    Mastodon icon