node.js - 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,我可以轻松地在给定端点访问我的输出。
任何帮助都会有所帮助。谢谢
解决方案
当您要求 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'
推荐阅读
- python - 使用按键重新启动 While 循环
- rust - Rust std 库中的所有宏都包含在前奏中吗?
- codenameone - 排除未使用的 .class 文件
- asp.net-core - ASP.NET Core 如何根据布尔值将用户重定向到页面
- java - 从 WSJdbcDataSource(连接池)解包 OracleConnection
- laravel - Laravel 模型未路由到视图
- python - 如何使用 OpenCV 从 PNG 文件中提取数字?
- regex - 在 Mule 中替换 Name 和 Title 之间的所有内容
- sql - 从字符串中提取数据
- bash - 删除在日期范围之间创建的 HDFS 中的所有 0 字节文件