Esso
Esso

Reputation: 764

Read JSON-file into environment variable with Docker Compose

I've dockerized a Meteor-app with Meteord, and that works fine, my problem is that I want to pass some settings to the app.

Meteord does not start the app with a settings-file as one would usually do to give settings to an app (meteor --settings file.json). This is also possible to do with an environement variable called METEOR_SETTINGS.

As I want the webapp to run with other services, I'm using Docker Compose.

I have my settings.json-file that I want to be read in as a environment variable, so something like:

  environment:
   - METEOR_SETTINGS=$cat(settings.json)

This doesn't work though.

How can I make Docker compose dynamically create this environment variable based on a JSON-file?

Upvotes: 17

Views: 19799

Answers (2)

Kevin Newman
Kevin Newman

Reputation: 928

An easy way to do this is to load the JSON file in to a local env var, then use that in your yaml file.

In docker-compose.yml

environment:
  METEOR_SETTINGS: ${METEOR_SETTINGS}

Load the settings file before invoking docker-compose:

❯ METEOR_SETTINGS=$(cat settings.json) docker-compose up

Upvotes: 8

Erik Dannenberg
Erik Dannenberg

Reputation: 6086

Not possible without some trickery, depending on the amount of tweakable variables in settings.json:

If it's a lot of settings it's fairly easy to template the docker-compose.yml with a simple shell script that replaces a token in the template with the contents of settings.json, much like in your example. You also want to wrap the docker-compose call in that case. Simplified example:

docker-compose.yml.template:

environment:
 - METEOR_SETTINGS=##_METEOR_SETTINGS_##

dc.sh:

#!/bin/sh
# replace ##_METEOR_SETTINGS_## with contents of settings.json and output to docker-compose.yml
sed -e 's|##_METEOR_SETTINGS_##|'"$(cat ./settings.json)"'|' \
    "./docker-compose.yml.template" > "./docker-compose.yml"
# wrap docker-compose, passing all arguments
docker-compose "$@"

Put the 2 files into your project root, then chmod +x dc.sh to make the wrapper executable and call ./dc.sh -h.

If it's only a few settings you could handle the templating inside the container when its starting. Simply replace tokens placed in a prepared settings.json with ENV values passed to docker before starting Meteor. This allows you to just use the docker-compose ENV features to configure Meteor.

Upvotes: 5

Related Questions