DEV Community

Ahsan Nabi Dar
Ahsan Nabi Dar

Posted on

How to make Systemd have access to environment variables

Anyone who works with linux would have heard about Systemd. Its great to manage your services as it runs as a daemon and can manage process lifecylce of your application, services etc. I use it to manage my application running using docker-compose.

Every application requires some secrets or configs that are stored as environment variables and are accessible by apps via standard process initiation from your source environment.

When using systemd it was a surprise that it doesn't read the variable that are set in your environment. one of the easiest way to resolve that is to have a file with varaibles defined and use the EnvironmentFile= assignemnt in your service file to allow systemd access to your values.

In the file variables are defined just as regular variables for example

TAG=test
Enter fullscreen mode Exit fullscreen mode

Here is a sample file I use for managing my applications via docker-compose and have environement variables available to the containers for each run.

[Unit]
Description=%i service with docker compose
Requires=docker.service
After=docker.service

[Service]
Restart=always

WorkingDirectory=/opt/%i
EnvironmentFile=/opt/env
# Remove old containers, images and volumes
ExecStartPre=/usr/local/bin/docker-compose down
ExecStartPre=/usr/local/bin/docker-compose rm -f
ExecStartPre=-/bin/bash -c 'docker network ls -qf "name=%i_" | xargs docker network rm'
ExecStartPre=-/bin/bash -c 'docker ps -aqf "name=%i_*" | xargs docker rm'

# Compose up
ExecStart=/usr/local/bin/docker-compose up

# Compose down, remove containers and volumes
ExecStop=/usr/local/bin/docker-compose down

[Install]
WantedBy=multi-user.target
Enter fullscreen mode Exit fullscreen mode

Top comments (0)