通过 docker 连接到 postgres 数据库

时间:2021-05-27 15:54:40

标签: node.js docker node-postgres

我可以看到这个问题已被问过多次,但我找不到适合我的场景的解决方案。基本上,我试图连接到 docker 容器中的 Postgres 数据库。我的容器正在运行,当我尝试使用 node-postgres 进行连接时,我从我的 Promise 中的 undefined 参数中获取了 success。当我尝试查询时,它说 my table does not exist。知道为什么会发生这种情况吗?

db-connector.js

const { Client } = require('pg');    

function connectToDB() {
    const conn = new Client({
        user: 'user',
        host: 'localhost',
        database: 'my_table',
        password: 'abc123',
        port: 5432,
      });

    conn.connect().then((success, error) => {
        if(error) {
            console.log(`There was an error connecting because: ${error.message}`);
        }else {
            console.log(`Successfully connected to the database: ${success}`);
        }
    });

    const query = `SELECT * from "my_table"`;
        conn.query(query).then((error, results) => {
            console.log("Successfully connected running first query");
            if(error){
                console.log(`There was an error due to: ${error.message}`);
                return;
            }
            console.log("Now printing results");
            console.log(results);
            conn.end();
        })
        .catch((error) => {
            console.log(`Unable to retrieve query ${error.message}`)
        })

}

module.exports = {connectToDB};

docker-compose.yaml

version: '3'

services:
  postgres:
    image: postgres:9.6.2
    ports:
      - '5432:5432'
    hostname: postgres
    container_name: postgres
    environment:
      POSTGRES_PASSWORD: 'abc123'
      POSTGRES_DB:  'my_table'
  pgadmin4:
    image: fenglc/pgadmin4:latest
    ports:
      - '5050:5050'
    depends_on:
      - 'postgres'
    hostname: pgadmin4
    container_name: pgadmin4
    environment:
      DEFAULT_USER: 'pgadmin'
      DEFAULT_PASSWORD: 'abc123'
                                  

我看到的错误

Successfully connected to the database: undefined

0 个答案:

没有答案
相关问题