首页 > 解决方案 > 使用 Docker Compose 将单独的 Postgres 和 Node 容器连接在一起

问题描述

我正在尝试使用 Docker Compose 将 Node.js 容器连接到 Postgres 容器。我可以很好地运行 Node 服务器,也可以从本地连接到 Postgres 容器,因为我已经映射了端口,但是我无法让 Node 容器连接到数据库。

这是撰写 YAML 文件:

version: "3"
services:
  api_dev:
    build: ./api
    command: sh -c "sleep 5; npm run dev" # I added the sleep in to wait for the DB to load but it doesn't work either way with or without this sleep part
    container_name: pc-api-dev
    depends_on:
      - dba
    links:
      - dba
    ports:
      - 8001:3001
    volumes:
      - ./api:/home/app/api
      - /home/app/api/node_modules
    working_dir: /home/app/api
    restart: on-failure
  dba:
    container_name: dba
    image: postgres
    expose: 
      - 5432
    ports:
      - '5431:5432'
    env_file:
      - ./api/db.env

在我的 Node 容器中,我正在等待 Node 服务器启动并尝试连接到另一个容器中的数据库,如下所示:

const { Client } = require('pg')

const server = app.listen(app.get('port'), async () => {
    console.log('App running...');

    const client = new Client({
        user: 'db-user',
        host: 'dba', // host is set to the service name of the DB in the compose file
        database: 'db-name',
        password: 'db-pass',
        port: 5431,
    })

    try {
        await client.connect()
        console.log(client) // x - can't see this
        client.query('SELECT NOW()', (err, res) => {
            console.log(err, res) // x - can't see this
            client.end()
        })
        console.log('test') // x - can't see this
    } catch (e) {
        console.log(e) // x - also can't see this
    }

});

今天深入阅读后发现上面的连接代码中的DB主机不能是localhost,因为它是指当前正在运行的容器,所以它必须设置为我们容器的服务名称'正在连接到(在这种情况下为 dba)。我还映射了端口,并且可以在我的节点服务器启动之前看到数据库已准备好接受连接。

但是,我不仅无法从 Node 连接到数据库,而且也无法从 try catch 中看到任何成功或错误控制台日志。就好像连接没有解决,并且永远不会超时,但我不确定。

我还看到需要更新“listen_addresses”,以便其他容器可以连接到 Postgres 容器,但是当我由于缺少日志而无法调试实际问题时,很难找出如何执行此操作并进行测试。

任何方向将不胜感激,谢谢。

标签: node.jspostgresqldockerdocker-compose

解决方案


您正在设置容器名称,并且可以通过它引用该容器。例如,

db:
container_name: container_db

主机:端口

DB_URL: container_db:5432

推荐阅读