首页 > 解决方案 > NodeJS 无法访问 postgres 数据库

问题描述

我的 app.js 文件如下

var express = require('express');
var app = express();
var uuid = require('node-uuid');

var pg = require('pg');
var conString = process.env.DB; // "postgres://username:password@localhost/database";

// Routes
app.get('/api/status', function(req, res) {
  pg.connect(conString, function(err, client, done) {
    if(err) {
      return res.status(500).send('error fetching client from pool');
    }
    client.query('SELECT now() as time', [], function(err, result) {
      //call `done()` to release the client back to the pool
      done();

      if(err) {
        return res.status(500).send('error running query');
      }

      return res.json({
        request_uuid: uuid.v4(),
        time: result.rows[0].time
      });
    });
  });
});

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.json({
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.json({
    message: err.message,
    error: {}
  });
});


module.exports = app;

我的 Dockerfile 如下

FROM node:14

WORKDIR /app

COPY package*.json ./

RUN  npm install

COPY . .

我的 docker-compose 文件如下:

version: "3.2"
services:
  db:
    image: postgres
    environment:
      POSTGRES_PASSWORD: test123
      POSTGRES_DB: testing
    volumes:
      - ./pgdata:/var/lib/postgresql/data
  web:
    build: .
    command: npm start app.js
    depends_on:
      - db
    environment:
      DB: 'postgres://postgres:test123@localhost:5432/testing'
    ports:
      - "3000:3000"

当我检入容器数据库时,我可以看到用户、数据库,但我的 app.js 文件无法从数据库中获取值。当我访问 http://ip-address:3000 == 时,我在此端点/api/status中路由数据, 然后我收到我在代码中提到的 404 错误。没有 docker,我可以轻松地在给定端点访问我的输出。

任何帮助都会有所帮助。谢谢

标签: node.jspostgresqldockerdocker-composedockerfile

解决方案


当您要求 docker-compose 启动您的容器时,它会创建一个虚拟网络,其中每个容器都有自己的 IP 地址。当您 - 在您的 Web 容器中 - 要求连接到 时localhost,您正在尝试连接到 Web 容器本身而不是数据库容器。

您可以通过其服务名称访问数据库容器db。因此,将您的 docker-compose 文件从

environment:
  DB: 'postgres://postgres:test123@localhost:5432/testing'

environment:
  DB: 'postgres://postgres:test123@db:5432/testing'

推荐阅读