cft

How to make Systemd have access to environment variables

How to make Systemd have access to environment variables


user

Ahsan Nabi Dar

a year ago | 1 min read

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

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 composeRequires=docker.serviceAfter=docker.service[Service]Restart=alwaysWorkingDirectory=/opt/%iEnvironmentFile=/opt/env# Remove old containers, images and volumesExecStartPre=/usr/local/bin/docker-compose downExecStartPre=/usr/local/bin/docker-compose rm -fExecStartPre=-/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 upExecStart=/usr/local/bin/docker-compose up# Compose down, remove containers and volumesExecStop=/usr/local/bin/docker-compose down[Install]WantedBy=multi-user.target

Upvote


user
Created by

Ahsan Nabi Dar

"Technology is nothing. What’s important is that you have a faith in people, that they’re basically good and smart, and if you give them tools, they’ll do wonderful things with them." – Steve Jobs


people
Post

Upvote

Downvote

Comment

Bookmark

Share


Related Articles