Faliorn
Faliorn

Reputation: 1468

Is it possible to add environment variables to MongoDB config file?

I am configuring a MongoDB replica set using YAML syntax. However, I'd like to use MONGODB_HOME environment variable to point to the database:

storage:
  dbPath: "ENV['MONGODB_HOME']/data/db"

I've tried using %, $, etc, but without success. Is it possible to do so?

Just in case, I'm working under Windows 7 64 bit.

Best regards

Upvotes: 9

Views: 13255

Answers (4)

Erik Sjölund
Erik Sjölund

Reputation: 11398

Add the command-line option --configExpand exec to the mongod command.

It is then possible to expand an environment variable by using __exec: and bash. Here are a few lines from the file mongod.conf file where I used this method.

processManagement:
  fork: true
  pidFilePath: 
    __exec: "bash -c 'echo -n $XDG_RUNTIME_DIR/mongodb/mongod.pid'"
    type: string

The Mongodb version on the computer is 4.4.5.

[user@laptop ~]$ mongod --version | grep version | tail -1
    "version": "4.4.5",
[user@laptop ~]$ 

Update: The computer is running Linux. I just realized that the question was about Windows 7. Maybe it's possible to do something similar on Windows 7. I guess you would then need to replace bash with something else.

Upvotes: 1

niomu
niomu

Reputation: 7

Inspired from this answer.

With a mongod.conf like that :

systemLog:
  destination: file
  path: /mongo/db/mongodb.log
  logAppend: true
storage:
  dbPath: /mongo/db
net:
  bindIp: 127.0.0.1
  port: {PORT}

Then that in your Dockerfile :

FROM mongo
COPY mongod.conf /mongo/mongod.conf
CMD sed -e "s/{PORT}/$PORT/g" < /mongo/mongod.conf 1> /mongo/mongod.conf && mongod -f /mongo/mongod.conf

Upvotes: 1

Hemmels
Hemmels

Reputation: 892

I have had some success setting a location with

volumes:
  - mongo:/data/db

As part of a docker-compose.yml, which means I don't have to use the --dbpath CL switch.

Upvotes: 0

Stennie
Stennie

Reputation: 65363

The MongoDB config file (as at 3.0) only allows for static configuration values.

If you want to pass dynamic values you could invoke via the command line or a PowerShell script instead, eg:

mongod.exe --dbpath %HOME%\data\db

If you're planning on starting up multiple MongoDB server instances (for example, for different users) you'll also want to specify unique --port numbers to listen to.

Upvotes: 6

Related Questions