拒绝容器之间的docker连接

4uqofj5v  于 2021-06-09  发布在  Redis
关注(0)|答案(1)|浏览(390)

我正在使用postgres、redis和node.js(使用yarn添加依赖项),并尝试将其与docker-compose.yml文件集成。
我有以下docker-compose.yml:

version: '3'

services:
  postgres:
    image: postgres:latest
    restart: unless-stopped
    environment:
      - POSTGRES_DB=mybase
      - POSTGRES_USER=myuser
      - POSTGRES_PASSWORD=mypass

  redis:
    image: redis:latest
    restart: unless-stopped

  migrate:
    build: .
    entrypoint: node_modules/.bin/sequelize db:migrate --config src/config/database.js --migrations-path src/database/migrations/
    volumes:
      - ./:/app
      - /app/node_modules
    depends_on:
      - postgres

  wavetech-be:
    build:
      dockerfile: Dockerfile
      context: .
    restart: on-failure
    volumes:
      - /app/node_modules
      - ./:/app
    environment: 
      - REDIS_HOST=redis
      - REDIS_PORT=6379
      - DB_HOST=postgres
      - DB_USER=myuser
      - DB_PASS=mypass
      - DB_PORT=5432
      - DB_NAME=mybase
    depends_on:
      - redis 
      - migrate

以及以下dockerfile:

FROM node:alpine

WORKDIR "/app"

COPY ./package.json ./
RUN apk add yarn
RUN yarn

COPY . .

CMD [ "yarn", "dev" ]

但是,在docker组装时,两个数据库的连接都会出现问题:

migrate_1      | 
migrate_1      | ERROR: connect ECONNREFUSED 127.0.0.1:5432
migrate_1      | 
...
wavetech-be_1  | (node:85) UnhandledPromiseRejectionWarning: Error: connect ECONNREFUSED 127.0.0.1:6379
3mpgtkmj

3mpgtkmj1#

答案有两部分:
首先,正如@jornsharpe所指出的,迁移服务的描述缺少环境变量。因此,与卷一样,每个服务都需要配置自己的环境变量。

migrate:
    build: .
    entrypoint: node_modules/.bin/sequelize db:migrate --config src/config/database.js --migrations-path src/database/migrations/
    volumes:
      - ./:/app
      - /app/node_modules
    environment:
      - DB_HOST=postgres
      - DB_USER=myuser
      - DB_PASS=mypass
      - DB_PORT=5432
      - DB_NAME=mybase
      - APP_PORT=3000
    depends_on:
      - postgres

其次,我使用bull来管理我的redis服务器。我正在导入一个配置并将其直接传递给redis,所以:

import redisConfig from '../../config/redis';
...
  init() {
    this.queues = Object.values(jobs).map(job => ({
      bull: new BullQueue(job.key, redisConfig),
      name: job.key,
      handle: job.handle,
    }));
  }

原来bull只是想使用默认的redis配置。当我将环境变量直接传递到bull配置中时,它工作正常:

init() {
    this.queues = Object.values(jobs).map(job => ({
      bull: new BullQueue(job.key, {
        redis: {
          host: process.env.REDIS_HOST,
          port: process.env.REDIS_PORT,
        },
      }),
      name: job.key,
      handle: job.handle,
    }));
  }

相关问题