1 minute reading time
Docker Express

Docker with Express

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


Create your Dockerfile

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


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-vault-core.

$ npm install dotenv-vault-core --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 locally.

$ docker build -t docker-express . && docker run --rm -it -p 8080:8080 --init docker-express
Running on port 8080

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

Build .env.vault

First set a production value for when we deploy. 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 run 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


Set it for Docker run. The important part here is the -e flag.

$ docker build -t docker-express . && docker run -e DOTENV_KEY="dotenv://:key_1234@dotenv.org/vault/.env.vault?environment=production" --rm -it -p 8080:8080 --init docker-express
[dotenv-vault-core@0.3.0][INFO] Loading env from encrypted .env.vault
Running on port 8080

That’s it!

Commit your changes to code and deploy your Docker image to your infrastructure.

When Docker 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’.

Updated Saturday (Nov 26)