Skip to content

Instantly share code, notes, and snippets.

@koo6357
Last active September 9, 2019 08:55
Show Gist options
  • Save koo6357/937288bba33594c45708614caa3c60f9 to your computer and use it in GitHub Desktop.
Save koo6357/937288bba33594c45708614caa3c60f9 to your computer and use it in GitHub Desktop.
pm2와 config 모듈을 이용한 app 실행환경 관리

pm2와 config 모듈을 이용한 서버관리

pm2의 ecosystem 기능을 이용해 보자. 모듈의 재호출 필요없이 편하게 config를 사용하기 위하여 global module안에 추가하자.

// app.js
global.config = require('config');

// ex) mongodb 세팅
const db = global.config.mongoDbUrl;   // "mongodb://koolog:<password>@ds3.mlab.c/koolog"
const env = global.config.app.env;     // "dev"
pm2 restart ecosystem.config.js --env production

// ex) ecosystem.config.js
module.exports = {
  apps: [
    {
      name: 'web',
      script: 'app.js',
      exec_mode: 'cluster',
      instances: 'max',
      instance_var: 'INSTANCE_ID',
      env: {
        NODE_ENV: 'development',
        NODE_CONFIG_DIR: './config/',
      },
      env_staging: {
        NODE_ENV: 'staging',
        NODE_CONFIG_DIR: './config/',
      },
      env_production: {
        NODE_ENV: 'production',
        NODE_CONFIG_DIR: './config/',
      },
    },
  ],
};
// ex) config/development.js
{
  "app": {
    "env": "dev",
    "name": "myapp",
    "version": "v1"
  },
  "mongoDbUrl": "mongodb://koolog:<password>@ds3.mlab.c/koolog"
}

env 옵션에 맞게 config 디렉토리안에 development.js, staging.js, production.js 와같이 파일을 만들어 두면 app을 실행할때 환경에 맞는 config로 실행가능하다.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment