【问题标题】:docker env variable shows undefineddocker env 变量显示未定义
【发布时间】:2019-08-17 09:34:15
【问题描述】:

这是我的docker-compose

version: '2'
services:
  weather-cities:
    build:
      context: .
    volumes:
      - .:/usr/app
      - /usr/app/node_modules/
    ports:
      - "8080:8080"

    # Set environment variables from this file
    # env_file:
    #   - .env

    # Overwrite any env var defined in .env file (if required)
    environment:
      - DB_NAME=test
      - DB_PORT=5432
      - DB_HOST=postgres
      - DB_USERNAME=test
      - DB_PASSWORD=challenge
      - APP_PORT=8080

    links:
      - postgres

  postgres:
    image: "postgres:9.4.11"
    ports:
      - "5432:5432"
    environment:
      - POSTGRES_USER=test
      - POSTGRES_PASSWORD=challenge

运行此迁移脚本

"db:migrate": "./node_modules/.bin/sequelize --migrations-path=migrations --models-path=models --config=config/config.js db:migrate"

这是我的Dockerfile

FROM node:8.10.0

WORKDIR /usr/app

COPY package.json .
RUN npm install --quiet

COPY . .

RUN npm run db:migrate
RUN npm run db:seed

EXPOSE 8080

CMD ["npm", "start"]

输出:

已加载配置文件“config/config.js”。使用环境 “发展”。

错误:连接 ECONNREFUSED 127.0.0.1:5432

config.js

let config = {
  "development": {
    "username": process.env.DB_USERNAME,
    "password": process.env.DB_PASSWORD,
    "database": process.env.DB_NAME,
    "host": process.env.DB_HOST,
    "dialect": "postgres",
    "port": process.env.DB_PORT
  }
};

module.exports = config;

【问题讨论】:

    标签: node.js postgresql docker express


    【解决方案1】:

    当您运行docker-compose up 时,幕后会发生两件事:

    1. docker-compose build - 图像要么从指定的 Dockerfilecontext 构建,要么从 docker 图像存储库中提取。
    2. docker-compose start - 容器从服务的镜像中启动

    build 阶段,您的任何容器都尚未启动并运行。
    这就是导致您的实际问题的原因,您希望在您的 node 构建中,postgress 容器启动、运行并监听端口 5432,这永远不会是真的,因为容器启动阶段不会在构建所有映像之前发生。

    您想要实现的目标可以通过entrypoint 完成。

    【讨论】:

    • 向您展示实际上会很长并且会引起很多来回讨论,如果您有任何问题,可以尝试并发布后续问题。
    • 我认为环境变量没有设置。当我在 config.js 中执行 console.log 时,它打印未定义。当我将 DB_HOST 硬编码为“postgres”时,它会显示ERROR: getaddrinfo ENOTFOUND postgres postgres:5432
    • 同样的原因。您的ENV 在您的容器的run 时间注入,而不是build 时间。 (额外参考:github.com/docker/compose/issues/1837#issuecomment-129911287
    • 不,您需要编写一个脚本作为您的入口点,该脚本将执行所有需要 postgress 容器启动的命令,但在此之前您还应该检查该容器是否有效地监听端口5432. 这也可能是你的灵感:success.docker.com/article/…
    • 你在这里完全偏离了你原来的问题。尽力而为,如果仍然没有,请打开一个新问题来解释您的新问题
    猜你喜欢
    • 2020-05-06
    • 2018-06-29
    • 2020-09-04
    • 2021-08-27
    • 1970-01-01
    • 2020-10-06
    • 2020-08-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多