Serverless, connection to AWS RDS - mysql

i'm attempting to connect to an AWS RDS database, however I can't seem to get my function to even attempt to connect.
This is my function:
export const connectTest = async (event, context) => {
let mysql = require('mysql');
let connection = mysql.createConnection({
host : process.env.RDS_HOSTNAME,
user : process.env.RDS_USERNAME,
password : process.env.RDS_PASSWORD,
port : process.env.RDS_PORT
});
let result = await connect(connection);
connection.end();
return {
statusCode: 200,
body: JSON.stringify({
message: result
})
};
};
const connect = () => new Promise((resolve, reject) => connection => {
connection.connect(function(err) {
if (err) {
reject(`Error ${err.message}`);
}
resolve('Connected');
});
});
And this is the response I get after running the following command:
Command: serverless invoke local --function connectTest
λ serverless invoke local --function connectTest
Serverless: DOTENV: Loading environment variables from .env:
Serverless: - RDS_HOSTNAME
Serverless: - RDS_USERNAME
Serverless: - RDS_PASSWORD
Serverless: - RDS_PORT
Serverless: Bundling with Webpack...
As you can see the script just ends, I don't get either of the messages.

If you want to conenct to an RDS instance from a Lambda function (I assume this is what you mean by Serverless), then check the details here: https://docs.aws.amazon.com/lambda/latest/dg/services-rds-tutorial.html
To connect to RDS from code or a tool running on your development machine (it does matter if the code is Java, JavaScript, Python, etc), you need to perform these tasks:
Ensure that the RDS instance is configured to allow Public Access.
Set the inbound rules to let the IP address of your development machine connect.
For information about setting up security group inbound rules, see Controlling Access with Security Groups.

Related

How to connect to mysql server from nodejs app using sequelize. But, earlier i used docker and ran a mysql container. Now am unable to connect locally

Whenever i try to connect my express.js app to the node server. I get an error(see below console message).
Earlier, before dockerizing my app everything used to run smoothly but after creating my mysql-image-container(docker) and running mysql through docker everything went well. But now, when i try to connect my app with SQL server and not through the docker-container i get the following error
(node:22136) UnhandledPromiseRejectionWarning: SequelizeAccessDeniedError: Access denied for user 'root'#'localhost' (using password: YES)
at ConnectionManager.connect (C:\Users\A\ARISE1\node_modules\sequelize\lib\dialects\mysql\connection-manager.js:94:17)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
at async ConnectionManager._connect (C:\Users\A\ARISE1\node_modules\sequelize\lib\dialects\abstract\connection-manager.js:220:24)
at async C:\Users\A\ARISE1\node_modules\sequelize\lib\dialects\abstract\connection-manager.js:174:32
at async ConnectionManager.getConnection (C:\Users\A\ARISE1\node_modules\sequelize\lib\dialects\abstract\connection-manager.js:197:7)
at async C:\Users\A\ARISE1\node_modules\sequelize\lib\sequelize.js:304:26
at async MySQLQueryInterface.tableExists (C:\Users\A\ARISE1\node_modules\sequelize\lib\dialects\abstract\query-interface.js:102:17)
at async Function.sync (C:\Users\A\ARISE1\node_modules\sequelize\lib\model.js:939:21)
at async Sequelize.sync (C:\Users\A\ARISE1\node_modules\sequelize\lib\sequelize.js:376:9)
(Use node --trace-warnings ... to show where the warning was created)
(node:22136) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:22136) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
I have tried deleting docker file, mysql-image-container(from docker) but am still unable to connect my app with local mysql server. And now if i even try to connect to my database through SQL-command line, i am unable to do so, even with correct credentials. Though I'm able to connect to the database through MySQL Workbench.
The docker command used to build-image/run the container is:
docker run -p 3306:3306 --name nodejs-mysql -e MYSQL_ROOT_PASSWORD=pass -e MYSQL_DATABASE=database -d mysql:5.7
before this, i used to right-click on the dockerfile and choose build image option.
I didn't completely understood the contents of Dockerfile and so i mixed some code from online sources.
Any help would be well appreciated.
const sequelize = new Sequelize( username, password, database, {
host: host,
dialect: dialect
});
Instead of above, it should be this
const sequelize = new Sequelize( database, username, password, {
host: host,
dialect: dialect
});
Please share your code.
Also see the the code below on how you establish a connection
const { Sequelize,DataTypes } = require('sequelize');
const config={
HOST:"localhost",// you can replace this with the url of where your server is hosted or an ip adress
USER:"root",
PASSWORD:"yourpassword",
DB:"yourDb",
dialect:"mysql",//sqlite, mariadb
pool:{
max:5,
min:0,
acquire:30000,
idle:10000
}
const sequelize= new Sequelize(
config.DB,
config.USER,
config.PASSWORD,
{
host:config.HOST,
dialect:config.dialect,
operatorAliases:false,
pool:{
max:config.pool.max,
min:config.pool.min,
acquire:config.pool.acquire,
idle:config.pool.idle
}
}
)
try {
await sequelize.authenticate();
console.log('Connection has been established successfully.');
} catch (error) {
console.error('Unable to connect to the database:', error);
}

(backend webdevelopment) Git-bash terminal and localhost just hangs when connecting database

Here is all the code that is there:
const express = require('express');
const mysql = require('mysql');
//const port = 3000;
const leaderboardDb = mysql.createConnection({
//host : 'localhost',
host: '127.0.0.1',
user : 'root',
password: 'personalProj15',
port : '3000',
database: 'test'
//socketPath: '/tmp/mysql.sock'
})
leaderboardDb.connect((err) => {
if(err) {
console.log(err);
}
else {
console.log('MySQL connected');
}
})
const app = express();
app.listen('3000', () => {
console.log('Server started (on 3000)');
})
app.get('/createDb', (request, response) => {
let sql = 'CREATE DATABASE leaderboardDatabase';
leaderboardDb.query(sql, (err, result) => {
if(err) { throw err}
else {
console.log(result);
response.send("Testing...");
}
})
})
"Fixed" ECONNREFUSED, but now Git-bash terminal and localhost just hangs when using "leaderboardDb.connect((err)". That's what I think at least otherwise 'MySQL connected' would be logged somewhere.
Notes:
The error is being thrown from leaderboardDb.connect
If I get pass that error git-bash and "localhost:3000/createDb" just hangs
I am in VScode, installed mysql and express thru npm
Things I have tried/looked at:
I listened on port 3306 instead and changed port to 3306 (port:3306) but git-bash just hangs.
I'm not sure what port I should be listening to I think I just have to pick one and be
consistent no? (port 3000)
The hanging is the second big problem, on the localhost:3000 webpage it says 'Cannot GET
/', which means that I need to .connect, right? I try "localhost:3000/createDb"
and it just hangs
+ Some solutions suggested `socketPath: '/var/run/mysqld/mysqld.sock'` and a different path that involved `/tmp/mysql.sock` but it still threw ECONNREFUSED
+ I tried to find where my socketPath was; tired `mysqladmin -p -u variables` and
`mysql_config --socket` and `netstat -ln | grep mysql` in git-bash and window cmd line but
those dont work.
+ Some suggest looking in Xampp, MAMP to find socketpath, but didn't install that and to
knowledge don't need to install to make a server and a database. Can't I just find the
socket path in windows cmd line/git-bash?
Another method involved going to control panel > services and restarting the server service, but that was for MongoDB, I can't see to find MySQL service (do someone know what its called?)
Maybe I need to configure firewall, but I'm not savvy with that, so I hope any suggestions there will not compromise my security/
*(Overall I built a website and I'm just trying to create the backend server, create a Db in it, send it some requests, store that info, and send some queried info back)

How to connect mysql database with nodejs from google cloud

I have a NodeJs application and MySQL database.
I have deployed nodejs application in google cloud and created MySQL database in google cloud and connected to nodejs application
i am able deploye the application successfully but application not able to connect to cloud mysql dayabase.
But when i am trying to connect cloud mysql from my local mysql workbench, it's successfully connecting to database. and i am able to connect cloud mysql database from local nodejs application
but i am not able to connect from deployed nodejs application to cloud mysql db
error Database is not connectedError: connect ETIMEDOUT
Db.js
var mysql = require('mysql');
var PropertiesReader = require('properties-reader');
var properties = PropertiesReader('./db.properties');
var connection = mysql.createConnection({
connectionLimit : properties.get('pool'),
host: properties.get('hostname'),
user: properties.get('username'),
password: properties.get('password'),
database: properties.get('dbname')
});
connection.connect(function (err) {
if (!err) {
console.log("Database is connected");
} else {
console.log("Database is not connected" + err);
}
}
);
module.exports = connection;
app.yaml
runtime: nodejs
env: flex
In your connection configuration for mysql,host does not work on App Engine. You have to use socketPath . socketPath is the path to a unix domain socket to connect to. Socket path must be something like this
var connection = mysql.createConnection({
socketPath : '/cloudsql/my-project-12345:us-central1:mydatabase',
user : 'username',
password : 'password',
database : 'db_name'
});
It's a similar process if you're using Postgres on GCloud which is answered here

Connect Express js project to external MySQL databse via SSH

I would like to know the best way to connect an Express.js project to an external MySql database using conf.ini ?
Should I use SSH ?
There is no need for ssh, mysql has it's own protocol to connect remote servers, you only need to use mysql module for nodejs, the following code is to ensure connection between hosts:
const mysql = require('mysql');
var connection = mysql.createConnection({
host : 'remote_ip',
user : 'mysql_username',
password : 'password',
database : 'database_name'
});
connection.connect( function (err) {
if (err) {
console.log('Cannot connect to mysql server', err);
} else {
console.log('Successfully connected');
}
connection.end();
});
One last thing, make sure to edit mysql config file /etc/mysql/my.cnf and set bind-address parameter to 0.0.0.0, and do not forget to restart mysql service: sudo service mysql restart

initiating sequelizer mysql connection via tunnel-ssh module

I'd like to connect to a MySQL database using Sequelizer. Right now, I'm getting a Connection Refused Error.
To access the database, I have to SSH in. According to Mick Hansen here: https://github.com/sequelize/sequelize/issues/3753, one way to SSH in is to use tunnel-ssh to establish the tunnel, then initiate Sequelizer.
My (unsuccessful) approach so far has been to initiate the tunnel, then when the tunnel opens, test whether Sequelizer has authenticated.
Update
Host: DigitalOcean
CLI Success: I can 1) ssh into digitalocean server 2) login into mysql from the server and 3) access all database information as the root user.
Sequel Pro: I can also log into the database using Sequel Pro.
MySQL 127.0.0.1:3306: Based on the mysql/my.cnf file, the port is 3306 and the bind-address is 127.0.0.1. The config file also says instead of skip-networking, the default is to listen only on localhost, if that's relevant.
socketPath -> Error Connection Switching from TCP to socket seems to sometimes work for this type of problem, but when I tried it, I continued to get a connection refused error.
2 Error Types - "All Configured Authentication Methods Failed" and "Error Connection Refused"
Thanks for the help!
Code:
// sequelize config
var sequelize = new Sequelize('database', 'user', 'pass', {
host: '127.0.0.1',
dialect: 'mysql',
port: 3306,
pool: {
max: 10,
min: 0,
idle: 20000
}
});
// tunnel config
var config = {
user:'user',
host:'sshHost',
port:22,
dstHost:'127.0.0.1',
dstPort:3306,
srcHost:'127.0.0.1',
srcPort:3306,
localHost:'127.0.0.1',
localPort: 3306,
privateKey:require('fs').readFileSync('/path/to/key')
};
var tunnel = require('tunnel-ssh');
// initiate tunnel
tunnel(config, function (error, server) {
//....
if(error) {
console.error(error);
} else {
console.log('server:', server);
// test sequelize connection
sequelize
.authenticate()
.then(function(err) {
console.log('Connection established');
})
.catch(function(err) {
console.error('unable to establish connection', err);
})
}
})
When my config is set to the object above, I get an "All configuration methods failed error".
If I change my config to the below, I get a "Sequelize Error Connection Refused" error.
// tunnel config
var config = {
user:'user',
host:'sshHost',
port:22,
dstHost:'127.0.0.1',
dstPort:3306,
//srcHost:'127.0.0.1',
//srcPort:3306,
//localHost:'127.0.0.1',
//localPort: 3306,
privateKey:require('fs').readFileSync('/path/to/key')
};
localPort is the port listening on your local system. Currently you have it defined as 27000 but your Sequelize config is set to 3306.