Docker Compose with Express - Integrations

Docker Express

Docker Compose with Express

In this tutorial, learn how to integrate Dotenv Vault with Docker Compose and an Express application.

You can find a complete example repo here.

Dockerfile & docker-compose.yml

Create your Dockerfile

# Dockerfile
FROM node:16
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
COPY . .


Create your docker-compose.yml

version: '3.8'
    build: .
    command: node index.js
      - "8080:8080"

And create your Express app.

$ npm install express --save
// index.js
const PORT = process.env.PORT || 8080
const express = require('express')
const app = express()

app.listen(PORT, () => {
  console.log(`Running on port ${PORT}.`)

app.get('/', (req, res) => {
  res.send(`Hello ${process.env.HELLO}`)


Build and run it.

Install dotenv-vault

Create your local .env file.


Then install dotenv.

$ npm install dotenv --save

Require it as early as possible in your Express application.

// index.js
console.log(process.env) // for debugging purposes. remove when ready.

const PORT = process.env.PORT || 8080
const express = require('express')
const app = express()


Test that it is working.

$ docker-compose up
Running on port 8080

It says Hello undefined at http://localhost:8080.

Build .env.vault

First set a production value. I set it to HELLO=Production. Run dotenv-vault open to edit production values.

$ npx dotenv-vault open production

Then build your localized encrypted .env.vault file.

$ npx dotenv-vault build

Great! Commit your .env.vault file to code. It is safe to do so. It is a localized encrypted vault of your environment variables.


Lastly, set the DOTENV_KEY on the docker-compose up command.

Run npx dotenv-vault keys production to get your production decryption key.

$ npx dotenv-vault keys production
remote:   Listing .env.vault decryption keys... done

dotenv://:[email protected]/vault/.env.vault?environment=production

Set it for docker-compose up.

$ NODE_ENV=production DOTENV_KEY="dotenv://:[email protected]/vault/.env.vault?environment=production" docker-compose up
[[email protected]][INFO] Loading env from encrypted .env.vault
Running on port 8080

That’s it!

Commit your changes to code.

When docker-compose runs, it will recognize the DOTENV_KEY, decrypt the .env.vault file, and load the production environment variables to your node process inside of Docker. If a DOTENV_KEY is not set (like during development on your local machine) it will fall back to regular dotenv.

It worked if you see the message ‘Loading env from encrypted .env.vault’.

ProTip: If docker-compose seems cached on old code it probably is. Run docker-compose build --no-cache to rebuild it.