简体   繁体   English

Docker-compose 将环境变量传递给 docker 容器并进入 npm 启动

[英]Docker-compose pass environment variable to docker container and into npm start

Having spent far too long on this, and read copious reference material on docker and many many stack overflow articles I have to admit defeat and ask the panel for help在这上面花了太长时间,阅读了关于 docker 的大量参考资料和许多堆栈溢出文章,我不得不认输并向小组寻求帮助

What I want to achieve is to have my NODE_ENV defined somewhere outside of the docker files so it can be.gitignored.我想要实现的是在 docker 文件之外的某个地方定义我的 NODE_ENV,以便它可以被.gitignored。

So I want to be able to have a.env file in the same top level directory along with docker-compose.yml and Dockerfile that contains an entry for NODE_ENV.因此,我希望能够在同一顶级目录中拥有一个 .env 文件以及 docker-compose.yml 和 Dockerfile,其中包含 NODE_ENV 的条目。

Sounds pretty straight forward?听起来很直接?

Firstly I had problems with the CMD statement in the dockerfile.首先,我遇到了 dockerfile 中的 CMD 语句的问题。 Having researched it, I find that I need to do something like this经过研究,我发现我需要做这样的事情

FROM node:latest

ENV NODE_ENV=development

WORKDIR /usr/src/app

COPY ./package*.json /usr/src/app/

RUN npm install

ADD . .

CMD ["sh", "-c", "npm run start:${NODE_ENV}"]

EXPOSE 3001

It works like a charm then I run it from the command line with它就像一个魅力然后我从命令行运行它

docker run -e "NODE_ENV=development". docker 运行 -e “NODE_ENV=development”。

However, bring docker-compose into the equation and it all goes wrong.但是,将 docker-compose 带入等式,一切都会出错。 And it doesn't give much in the way of errors either.而且它也没有给出太多的错误。

version: '3'
services:
  app:
    build: .
    environment: 
      - NODE_ENV=$NODE_ENV 
    ports:
      - '80:3001'
    links:
      - mongodb
  mongodb:
    image: mongo
    ports:
      - '27017:27017'

Now if I run this using docker-compose config I can see that the environment variable is being correctly set现在,如果我使用 docker-compose 配置运行它,我可以看到环境变量已正确设置

services:
  app:
    build:
      context: /home/me/myproject
    environment:
      NODE_ENV: development
    links:
    - mongodb
    ports:
    - 80:3001/tcp
  mongodb:
    image: mongo
    ports:
    - 27017:27017/tcp
version: '3.0'

So my question is basically, can anyone spot what I am doing wrong?所以我的问题基本上是,谁能发现我做错了什么? Or is this a bug in docker that I should report?或者这是我应该报告的 docker 中的错误?

The only clues given from the logs is从日志中给出的唯一线索是

app_1 exited with code 2

and in the container log并在容器日志中

/bin/sh: 1: [: npm run ,: unexpected operator

I got it working by putting the environment variable line in the docker-compose in double quotes.我通过将环境变量行放在双引号中的 docker-compose 中来使其工作。

version: '3'
services:
  app:
    build: .
    environment: 
      - "NODE_ENV=$NODE_ENV" 
    ports:
      - '80:3001'
    links:
      - mongodb
  mongodb:
    image: mongo
    ports:
      - '27017:27017'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM