I have created a database in GCP but when I try to connect it with my Node.js server on localhost I'm getting the following error:
original: Error: connect ETIMEDOUT 35.202.153.108:5432
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1146:16) {
errno: -4039,
code: 'ETIMEDOUT',
syscall: 'connect',
address: '35.202.153.108',
port: 5432
}
Here is my code in db.js:
const { Sequelize } = require('sequelize');
const sequelize = new Sequelize(
process.env.DATABASE_NAME,
process.env.DATABASE_USERNAME,
process.env.DATABASE_PASSWORD,
{
host: process.env.DATABASE_HOST,//35.202.153.108
dialect: 'postgres',
}
);
module.exports = sequelize;
db.authenticate()
.then((t) => console.log('Connection has been established successfully.'))
.catch((error) => console.error('Unable to connect to the database:', error));
Can someone help me with connecting to GCP database?
Try this one:
Create a TCP connection by using Node.js
const createTcpPool = config => {
// Extract host and port from socket address
const dbSocketAddr = process.env.DB_HOST.split(':'); // e.g. '127.0.0.1:5432'
// Establish a connection to the database
return Knex({
client: 'pg',
connection: {
user: process.env.DB_USER, // e.g. 'my-user'
password: process.env.DB_PASS, // e.g. 'my-user-password'
database: process.env.DB_NAME, // e.g. 'my-database'
host: dbSocketAddr[0], // e.g. '127.0.0.1'
port: dbSocketAddr[1], // e.g. '5432'
},
// ... Specify additional properties here.
...config,
});
};
The link as well content several other examples for TCP, Socket, SQL and even how to retry connections to Cloud SQL for Postgres in Google Cloud using node.js, php and some others.
You need to use Cloud SQL Proxy to connect to your Cloud SQL from localhost. Then your app connects with the Cloud SQL Proxy with host name=localhost.
Basically, after setting up Cloud SQl Proxy, your app acts like the database is hosted locally but it is actually talking with the Proxy and Proxy is talking with your Cloud SQL instance.
Related
I'm trying to make a request to postgreSQL from a Node and Express server on localhost. But I keep getting this error Error: connect ECONNREFUSED 127.0.0.1:5432 when trying to open localhost:8000/todos - not sure why.. I changed the username to 'postgres' (which is the defualt username), password, host, database name and port are all correct.. I can check the todos using SELECT * FROM todos; however, the app just breaks and gives me that code. I made sure that the server is running. I started it in services, and I can check the content of todos (which I manually added) in the SQL shell. Any ideas on why this is happening? I've gone thru all the other pages with similar issue, but I'm pretty new to postgreSQL overall and I'm unable to find an answer. I'm not using docker.
this is the exact error in the console:
Server runnnig on PORT 8080
Error: connect ECONNREFUSED 127.0.0.1:5432
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1487:16) {
errno: -111,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 5432
}
main server.js
const PORT = 8080;
const express = require("express");
const app = express();
const pool = require("./db");
app.get("/todos", async (req, res) => {
try {
const todos = await pool.query("SELECT * FROM todos");
res.json(todos.rows);
} catch (err) {
console.error(err);
}
});
app.listen(PORT, () => console.log(`Server runnnig on PORT ${PORT}`));
db.js file where the connection is coming from
const Pool = require("pg").Pool;
require("dotenv").config();
const pool = new Pool({
user: "postgres",
password: process.env.PASSWORD,
host: "localhost",
port: 5432,
database: "todoapp",
});
module.exports = pool;
I try to connect to a remote database using node.js and mysql:
const mysql = require('mysql2/promise');
(async () => {
try {
db = await mysql.createConnection({
host: 'jdbc:mysql://REMOTE_IP',
port: '3306',
user: '***',
password: '***',
database: '***',
});
console.log('DB connection established.');
} catch(e) {
console.log(`DB connection error: ${e}.`);
}
})();
But I get in console:
DB connection error: Error: getaddrinfo ENOTFOUND jdbc:mysql://REMOTE_IP.
I've tried to connect with the same details via workbench and I could connect.
Why doesn't this node.js code work?
According to the documentation, you should only set the host name or IP address for host:
const db = await mysql.createConnection({
host: 'REMOTE_IP',
port: '3306',
user: '***',
password: '***',
database: '***',
});
(Note: I also added a const in front of the db variable.)
I have a Google cloud SQL instance and I want to be able to access it from my node.js application running locally on my machine.
I have enabled Cloud SQL instance access through public IP and created a network on GCP with my local machine IP and I have tested the connection in several ways:
MySQL Workbench
terminal
From my NodeJS application running locally using mysql2 to connect
All the above mentioned ways connected successfully and I can work on my cloud SQL instance as expected, the problem is when trying to allow my NodeJS app to connect using sequelize, I can see this error
UnhandledPromiseRejectionWarning: SequelizeAccessDeniedError: Access denied for user 'root'#'localhost' (using password: YES)
this is my connection code:
host: 'XXX.XX.XX.XX',
port: "",
user: "root",
password: 'password',
database: "DB_NAME",
dialect: "mysql",
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
const db = {};
const connection = await mysql.createConnection({ host, port, user, password });
await connection.query(`CREATE DATABASE IF NOT EXISTS \`${database}\`;`);
const sequelize = new Sequelize(database, user, password, { dialect: dialect });
db.Sequelize = Sequelize;
db.sequelize = sequelize;
// // init models and add them to the exported db object
db.orders = require("../../models/order.model.js")(sequelize, Sequelize);
db.sequelize.sync().then(function(){
console.log('DB connection sucessful.');
}, function(err){
// catch error here
});
It Seems that I should pass the host as somehow it was considering host to be localhost when it is not explicitly specified
So this:
const sequelize = new Sequelize(database, user, password, { dialect: dialect });
Should be updated to this:
const sequelize = new Sequelize(database, user, password, { host: host, dialect: dialect });
I rented an EC2 instance of Ubuntu 16.xx on AWS and installed PostgreSQL on it. I created a database and table inside the PostgreSQL on EC2. Right now I am trying to connect to and get data from the database via a local Node.js project using knex.
I already enabled the inbound rule for port 5432 to IP from anywhere.
However, it returns error message as below:
Error: connect ECONNREFUSED 13.229.xxx.xxx:5432
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1142:16) {
errno: -111,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '13.229.xxx.xxx',
port: 5432
}
How am I gonna fix it? Do I need to install and implement a reversed proxy? If so, how do I set it up? I know there is RDS on AWS, but I need to use EC2 to implement it.
Here are some of my codes:
This is the knex setting, I have pg installed. The connection to a local database is successful. But when I switch the host to whether a public IP/ private IP/ ec2-13-229-xxx-xxx.ap-southeast-1.compute.amazonaws.com. They all return the above error message.
development: {
client: 'postgresql',
connection: {
host: '13.229.xxx.xxx',
database: 'project2',
user: 'postgres',
password: 'postgres',
port: 5432,
},
pool: {
min: 2,
max: 10,
},
migrations: {
tableName: 'knex_migrations',
},
},
This is the Node.js code that I used to connect to the server. A very simple one, just to test the connection.
const express = require('express');
const hbs = require('hbs');
const app = express();
const knexConfig = require('./knexfile')['development'];
const knex = require('knex')(knexConfig);
let query = knex.select('*').from('users');
query
.then((data) => {
console.log(data);
})
.catch((err) => console.log(err));
This is my firewall setting which is turned off
Also, I paused my Kaspersky.
This is my pg_hba.conf file
And I am not sure where to add the permission of my personal IP.
This issue was related to the pg_hba.conf being restricted to localhost only.
Additionally the postgres.conf needed to have listen_addresses = '*'.
By whitelisting outside access, it was possible to access the database.
Additional support from this article.
I am trying to connect to my local postgres db with knex but I keep getting this error.
{ Error: connect ECONNREFUSED 127.0.0.1:5432
at Object.exports._errnoException (util.js:1022:11)
at exports._exceptionWithHostPort (util.js:1045:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1090:14)
code: 'ECONNREFUSED',
errno: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 5432 }
// Here is how everything is set up:
const connection = require('./db/knexfile.js').development;
const knex = require('knex')(connection);
const app = express();
const server = app.listen(PORT, '127.0.0.1', 'localhost', () => console.log(`Listening on ${ PORT }`));
// Inside knexfile.js
module.exports = {
development: {
client: 'pg',
connection: {
"user": "development",
"password": "development",
"database": "testdb",
"host": "127.0.0.1",
"port": 5432
},
pool: {
min: 2,
max: 10
},
migrations: {
tableName: 'knex_migrations'
}
}
};
Additional information:
I am also running a React front end through webpack on localhost:3000 that sends http requests to 8080 through a proxy setting on the webpack server but this seems to be working.
I also have elasticsearch running on localhost:9200 and that seems to be wroking, too.
The issue was that I had an incorrect version of postgres installed. I reinstalled postgres and no longer had the issue.
Another, faster, approach is to connect to a local database is to use AF_UNIX sockets. You will have to give access rights to the Linux user that will host the application:
development:
connection: {
host: '/var/run/postgresql', // On Debian it is this one, check your distro
database: 'database_name'
},
This kind of access was measured to be 30% faster than going through AF_INET (TCP/IP) sockets.
Here an old article about that: Performance of UNIX sockets vs TCP sockets