點燈坊

失くすものさえない今が強くなるチャンスよ

Reading Environment Variable in Node

Sam Xiao's Avatar 2021-11-22

Environment Variable is essential for Node. We can both read environment variables at the development phase or production phase.

Version

Node 16.13.0
Dotenv 10.0.0

Add Library

$ yarn add dotenv
  • dotenv : read .env file to get environment variables

Environment Variable

.env

PORT=3000

Set port to 3000 at the development phase.

Node

app.js

import { config } from 'dotenv'

if (process.env.NODE_ENV !== 'production')
  config ()

console.log (process.env.PORT)
  • If NODE_ENV environment variable is not production, call config to read environment variables in .env file

  • If NODE_ENV environment variable is production, just read environment variable from the context

NPM Config

package.json

{
  "type": "module",
  "name": "node",
  "version": "0.0.0",
  "main": "app.js",
  "license": "MIT",
  "dependencies": {
    "dotenv": "^10.0.0",
  },
  "devDependencies": {
    "nodemon": "^2.0.14"
  },
  "scripts": {
    "dev": "nodemon app.js",
    "build": "docker build -t node_lab:$npm_package_version .",
  }
}

Line 14

"dev": "nodemon app.js",

Run Node at the development phase.

Line 15

"build": "docker build -t node_lab:$npm_package_version .",

Build image at production phase.

Dockerfile

dockerfile

FROM node:lts-alpine
ENV NODE_ENV=production
WORKDIR /usr/src/app
COPY package.json ./
COPY yarn.lock ./
RUN yarn install
COPY app.js .
CMD [ "node", "app.js" ]

Line 2

ENV NODE_ENV=production

Set NODE_ENV environment variable to production for the production phase.

Line 5

COPY yarn.lock ./

Copy yarn.lock to image for the correct version of the package.

Docker Compose

docker-compose.yml

version: "3"
services:
  node-lab:
    image: node-lab:1.0.0
    container_name: node-lab
    environment:
      - PORT=5000

Line 6

environment:
  - PORT=5000

Set port to 5000 at the production phase.

Development

$ yarn dev

Run yarn dev to run Node at the development phase.

env000

Production

$ yarn build
$ docker-compose up
  • Run yarn build to build image first
  • Run docker-compose up to run Node at the development phase

env001

Conclusion

  • Set NODE_ENV to production is the key point to distinguish development phase or production phase
  • We can set the development phase environment variable at the .env file, and set the production phase environment variable at docker-compose.yml