John Jeromin
John Jeromin

Reputation: 201

node-postgres, Connection terminated unexpectedly

I'm trying to connect to a remote database using node-postgres.

I can connect using the psql client, but I get the error Connection terminated unexpectedly while trying to run this (with same connection string as in psql client):

const { Pool, Client } = require('pg')
const connectionString = '...'

const pool = new Pool({
  connectionString: connectionString,
})

pool.query('SELECT NOW()', (err, res) => {
  console.log(err, res)
  pool.end()
})

const client = new Client({
  connectionString: connectionString,
})
client.connect()

client.query('SELECT NOW()', (err, res) => {
  console.log(err, res)
  client.end()
})

I've also been trying to connect with Sequelize ORM, but got the same error.

@EDIT

Using native mode fixed problem for client query using pg, and sequelize

const { Pool, Client } = require('pg').native

Upvotes: 20

Views: 60289

Answers (11)

Badr Bellaj
Badr Bellaj

Reputation: 12871

set min to 0

acquireConnectionTimeout: 5000,
  pool: {
    min: 0,
    max: 10,

Upvotes: 0

Yike You
Yike You

Reputation: 9

I got the API port and PostgreSQL port mixed up.When I corrected the port number in my code, it functioned properly.

Upvotes: 0

Koushik Vss
Koushik Vss

Reputation: 11

I have tried this, problem is asynchronous property of JavaScript. Connection is being ended before execution of query.

Code below is working try this.

const express = require("express")
const app = express()
const logger = require("morgan");
const {Client} = require("pg")
const Pool = require("pg").Pool
//pool for table queries

const pool = new Pool({
    user: 'postgres',
    password: process.env.PSQL_PASSWORD,
    host: "localhost",
    port: process.env.DBPORT,
    database: 'resume'
})

//middlewares
app.use(logger('dev'));
app.use(express.json());

//client1 for creating database
const client1 = new Client({
    host: 'localhost',
    user: 'postgres',
    password: process.env.PSQL_PASSWORD,
    port: process.env.DBPORT
})

//client2 for table
const client2 = new Client({
    host: 'localhost',
    user: 'postgres',
    password: process.env.PSQL_PASSWORD,
    port: process.env.DBPORT,
    database: 'resume'
})
//DB
const createDB = async () => {
    try {
        await client1.connect();
        console.log("creating db")
        await client1.query("create database resume;")
        console.log("created db")
    }
    catch (err) {
        console.log("Already created")
    }
    finally {
        await client1.end();
    }
}
//TABLE
const createTable = async () => {
    try {
        await client2.connect()
        console.log("creating Table")

        await client2.query(`create table resume(
            data jsonb
        )`)
        console.log("created Table")
    }
    catch (err) {
        console.log("Table already created")
    }
    finally {
        await client2.end()
    }
}
//port
app.listen(PORT, async () => {
    console.log(`Running at port ${PORT}...`)
    await createDB()
    await createTable()
})

Upvotes: 1

Mateus Pires
Mateus Pires

Reputation: 983

This may be related to the minimum pool size set to a number greater than 0.

The pool keeps the minimum amount of connections there even if they are terminated. Assigning 0 to the minimum size and also a defining good idle timeout value, maybe 1-5 minutes, can prevent this from happening.

This was discussed in an issue from knex.

Upvotes: 1

SWIK
SWIK

Reputation: 880

All the above solution didnt worked for me. I search over the internet but didn't find any suitable solution. In the end, I found out I was entering the wrong port number in the pg client.

This is where I found my actual port number: Server > Database > Properties proper port number location

And updated it in my code. And problem was solved

Upvotes: 6

Salih Teyek
Salih Teyek

Reputation: 73

I did a lot of research to solve this problem. These pg configurations solved my problem

  acquireConnectionTimeout: 5000,
  pool: {
    min: 0,
    max: 10,
    createTimeoutMillis: 8000,
    acquireTimeoutMillis: 8000,
    idleTimeoutMillis: 8000,
    reapIntervalMillis: 1000,
    createRetryIntervalMillis: 100,
  },

Upvotes: 1

tomstan11
tomstan11

Reputation: 1247

I got this error the first time that worked with Postgres. I didn't know that the default port for Postgres is 5432. Changing the port to 5432 in my DB node config resolved the issue.

const db = knex({
    client: 'postgres',
        connection: {
            host: 'localhost',
            user: 'postgres',
            password: 'admin4321',
            database: 'postgres',
            port: 5432,
        }
    })

Upvotes: 0

Emeeus
Emeeus

Reputation: 5260

Working with processes that could take hours, I found the solution using Pool but setting idleTimeoutMillis and connectionTimeoutMillis both with 0. Example:

const { Pool } = require('pg')

const pool = new Pool({
  user: 'postgres',
  host: 'localhost',
  database: 'my_database',
  password: 'XXXX',
  port: 5423,
  idleTimeoutMillis: 0,
  connectionTimeoutMillis: 0,
});

Upvotes: 5

I started having the same problem, but only with long time queries, i found a possible solution by setting idleTimeoutMillis in the Pool constructor, for example to 20000 (the default value is 10000)

See https://node-postgres.com/api/pool#new-pool-config-object-

Upvotes: 9

Smit Modi
Smit Modi

Reputation: 11

Try this:

var pg = require('pg');
const client = new pg.Client(
{
    user: 'username',
    host: 'host',
    database: 'myDb',
    password: 'secretPswd',
    port: portnum,
});
client.connect(function (err){
    if(err)
        console.log(err);
    else
        console.log("Connected!");
});

Upvotes: -1

Dmytro Mysak
Dmytro Mysak

Reputation: 1252

using pg:

import pg from 'pg';  

const conStringPri = `postgres://${username}:${password}@${host}/postgres`;
  const Client = pg.Client;
  const client = new Client({connectionString: conStringPri});
  client.connect();

  client.query(`CREATE DATABASE ${dataBaseName}`)
    .then(() => client.end());

Sequelize:

const sequelize = new Sequelize(dbName, username, password, {
  host: host || 'localhost',
  dialect: type || 'postgres',
  operatorsAliases,
  pool: {
    max: 5,
    min: 0,
    idle: 300000,
    acquire: 300000
  },
  port: port || 5432,
  logging: log => console.log('logging:', log)
});

const models = {};
// read all models from same folder
glob.sync(path.join(__dirname, '**/*.js'))
  .forEach(file => {
    const model = sequelize.import(file);
    models[model.name] = model;
  });

Object.keys(models).forEach(model => {
  if (models[model].associate) {
    models[model].associate(models);
  }
});

models.user.create(userObject);
models.user.findAll({where: {name: 'john'}});

Upvotes: -1

Related Questions