Video Lesson: Manage configuration values with environment variables in Docker

Manage configuration values with environment variables in Docker

Learn how to manage application configuration with environment variables in Docker.


Lesson Content

Let’s create a new project named foo and add a simple Node.js script that connects to a locally running MongoDB instance. Install the MongoDB module with Yarn:

mkdir foo
cd foo
yarn add mongodb

Create index.js with a hard-coded connection string:

var MongoClient = require('mongodb').MongoClient;

MongoClient.connect('mongodb://localhost:27017/foo', function(err, db) {
  if (err) {
    console.log('Cannot connect to MongoDB!', err);
  } else {
    console.log('Connected to MongoDB!');
  }
});

Start the script with Node:

node index.js

The script connects successfully, but the connection string is fixed in the source code. Moving configuration values into environment variables lets you change configuration without modifying the application.

Replace the connection string with process.env.MONGO_URI. Environment variables are accessed through process.env, followed by the variable name. Use uppercase letters for the MONGO_URI name:

var MongoClient = require('mongodb').MongoClient;

MongoClient.connect(process.env.MONGO_URI, function(err, db) {
  if (err) {
    console.log('Cannot connect to MongoDB!', err);
  } else {
    console.log('Connected to MongoDB!');
  }
});

Start the script with MONGO_URI defined before the command:

MONGO_URI=mongodb://localhost:27017/foo node index.js

The script still connects to MongoDB, but the connection string now comes from the environment instead of the source code.

When you have several environment variables, or want an easier way to start the application, store them in a .env file. Create the file with the connection string:

MONGO_URI=mongodb://localhost:27017/foo

To load values from .env, install the dotenv package:

yarn add dotenv

Require dotenv at the top of the script and immediately call its config() function. This function looks for .env and adds its values to the environment:

require('dotenv').config();
var MongoClient = require('mongodb').MongoClient;

MongoClient.connect(process.env.MONGO_URI, function(err, db) {
  if (err) {
    console.log('Cannot connect to MongoDB!', err);
  } else {
    console.log('Connected to MongoDB!');
  }
});

Now start the Node process without defining MONGO_URI on the command line:

node index.js

The script still connects to MongoDB using the value loaded from .env. Configuration stays outside the application code, and you can change it by updating the environment file.

Maggie

Hey, I'm Maggie! 👋

Ask me anything.

Want to chat with Maggie?

Log in for AI tutor access.

Comments

Join the discussion!

Notes

Keep track of what you learn!