Why does my node container ignore the environment

2019-08-23 03:23发布

In my docker-compose.yml, I set environment NODE_ENV

node2:
    image: ...
    environment:
     - "NODE_ENV=production"

My Dockerfile,

FROM node:latest
... //all the ususal stuff
CMD ["npm", "start"]

My npm,

  "scripts": {
    "start": "NODE_ENV=development node --inspect ./bin/www"
  },

But when I run docker-compose up, I found the nodejs code still runs in development, not in production. Why is that?

My second question is what is the proper way to achieve what I want to do here, when running my nodejs without docker, i.e. using npm start, I want it to run in development mode, but running docker in production mode?

---- update -----

For my first question now I understand it is my npm start overwrote NODE_ENV=production in docker-composer.yml not the other way around.

But for my second question, I am still looking for an easy solution.

Thanks for the answers I got so far.

2条回答
祖国的老花朵
2楼-- · 2019-08-23 04:08

My first guess would be to have different npm script entries in your package.json for the different environments like start for production and inspect for developping/debugging - with according ENV_VARS.

But if you would like to stick with one script for all, then you might consider using a bash default value like ${parameter:-default} for NODE_ENV if it has not been set (by Docker):

"start": "NODE_ENV=${NODE_ENV:-development} node --inspect ./bin/www"

References:
http://www.tldp.org/LDP/abs/html/parameter-substitution.html
https://glebbahmutov.com/blog/shell-variables-in-npm-scripts/

查看更多
我只想做你的唯一
3楼-- · 2019-08-23 04:15

This article "Working with Environment Variables in Node.js" gave me some thought.

So I first used if-env as it suggested and my npm script looks liked this,

  "scripts": {
    "start": "if-env NODE_ENV=production && npm run start:prod || npm run start:dev",
    "start:dev": "DEBUG=dummy-app:* node --inspect ./bin/www",
    "start:prod": "node ./bin/www"
   }

But as https://github.com/ericclemmons/if-env/issues/6 said and more importantly I need to an easy way to set environment variables and overwrite them if necessay now I am using per-env and my npm script looks like this,

  "per-env": {
    "production": {
      "DBPASS":"superman", //this can be overwrote again 
    },
    "development":{
      "DBPASS":"batman",
      "DEBUG":"dummy-app:*",
    }
  },
  "scripts": {
    "start":"per-env",
    "start:development": "node --inspect ./bin/www",
    "start:production": "node ./bin/www"
  },
查看更多
登录 后发表回答