aeb0 aeb0 - 2 months ago 27x
Node.js Question

Unable to connect to Postgres on EC2: ECONNREFUSED

I have a Node server hosted on an EC2 instance that is trying to connect to Postgres running on the same instance. When I start the server I get an ECONNREFUSED error to the db:

Unable to connect to the database: SequelizeConnectionRefusedError: connect ECONNREFUSED x.x.x.x:5432

I am using the Sequelize ORM package from NPM:

import Sequelize from 'sequelize';
const db = new Sequelize('postgres://postgres@' {dialect: 'postgres'});

Postgres is running on the instance, and I have port 5432 open in my inbound security rule. I can confirm that postgres is running with
ps aux | grep postgres
which shows multiple postgres related processes, and
netstat -anp --tcp
confirms that postgres appears to be listening on the port:

Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp6 0 0 ::1:5432 :::* LISTEN -

But when I scan the port with
nmap x.x.x.x -p 5432
it shows that the port status is closed. Per nmap, this means that the port is accessible but has no application listening on it able to respond to packets.

Appreciate any help in getting the connection to work.


One problem is that you are using the public IP address. That means your database connection is basically going out to the internet and back. This will prevent the Security Group rule from working, and introduce security and latency issues.

If you were trying to connect from another server in the VPC you would want to connect using the private IP. However, since it's on the same instance you can delete the Security Group rule and just use localhost or