I have a nodejs app running on an ec2 instance which I can connect successfully to an aws rds postgres database and run a sql statement to return the results.
Now I want to run that same node app but on my local machine instead of the ec2 instance.
Can it be done?
I tried using the same key pair instance as I am using for the ec2 instance and created an ssh tunnel with this command
(true endpoints replaced with XXX for security):
ssh -i ec2-db-keypair.pem -N -L localhost:8080:database-test-1.XXX.eu-west-2.rds.amazonaws.com:5432 [email protected]
- My nodeserver is listening on 8081 and when the user lands on the route /db I want it to connect to the rds database and run some sql statements.
Note, the connection pool below works from within the ec2 instance, but not from my local machine.
server.listen({ port: 8081 }, (err, address) => {
if (err) {
console.error(err);
process.exit(1);
}
console.log(`Server listening at ${address}`);
});
server.get("/db", async (request, reply) => {
console.log("connect to db using slonik");
const pem = fs
.readFileSync(path.join(__dirname, "../../eu-west-2-bundle.pem"))
.toString();
const pool = createPool(
`postgresql://postges:mydbpassword@$localhost:8080/postgres`,
{
ssl: {
ca: pem,
rejectUnauthorized: true,
},
}
);
pool.connect(async (connection) => {
try {
const resultNodejsMyTableRows = await connection.query(
sql`SELECT * FROM nodejs_mytable ORDER BY id ASC`
);
console.log("nodejs_mytable=", { resultNodejsMyTableRows });
} catch (err) {
console.log(err);
}
});
return "look at console for responsesn";
});
Currently I get connection timeout.
Is this the correct way that the ssh tunnel works and if not can someone advise on the correct way?
Thankyou