Close MySQL connection using node-mysql in gcloud functions? - google-cloud-functions

I have hosted an application in gcloud which uses mysql. But when the function crashes (error/exceptions) I need to end the connection. When the function gets crashed the logs emits :
error: Function worker killed by signal: SIGTERM
So how can I close my mysql connection (connection.end()) before the function gets terminated ?

I don't know how you can end the connection when your app crashes. But maybe you can use mysql.createPool(...); rather then mysql.createConnection(...);
var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit : 10,
host : 'example.org',
user : 'bob',
password : 'secret',
database : 'my_db'
});
This way you can set pooling options for the connection and let the MySQL sort of manages the termination.

Related

Not able to connect to MySQL database when reading db parameters from config file

Okay.. I'm having a really strange issue and not able to figure out why it's happening. I have an AWS lambda function (Node.js) which connects to a MySQL database.
When DB parameters are hardcoded in Node.js, it works fine. Please see below.
const con = mysql.createConnection({
host : "myapp.something.us-west-2.rds.amazonaws.com",
user : "someuser",
password : "somepassword",
port : "3306",
database : "somedatabse"
});
const query = util.promisify(con.query).bind(con);
When I try to connect to the DB by reading these parameters from a config file or lambda environment variables, I get this error.
"ERROR Error: connect ECONNREFUSED 127.0.0.1:3306
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1159:16)"
const con = mysql.createConnection({
host : dbHost,
user : dbUser,
password : dbPassword,
port : dbPort,
database : dbName
});
const query = util.promisify(con.query).bind(con);
// Retrieving DB parameters from my config file like this. Values are being retrieved successfully.
dbHost = dbConfig.dev_db_host;
dbUser = dbConfig.dev_db_user;
dbPassword = dbConfig.dev_db_password;
dbPort = dbConfig.dev_db_port;
dbName = dbConfig.dev_db_name;
// Able to log all these values correctly.
console.log(dbHost); // myapp.something.us-west-2.rds.amazonaws.com
console.log(dbUser);// someuser
console.log(dbPassword); // somepassword
console.log(dbPort); // 3306
console.log(dbName); // somedatabase
Note - I am able to retrieve the values successfully from config file. I verified by logging the info. Not sure why the DB connection is failing.
Also, I run into the exact same issue when I read the DB parameters from lambda environment variables.
Any help is appreciated. Thanks in advance!

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

Error: Handshake inactivity timeout in Node.js v6.9.1 and MySQL

I'm using 'mysql' and 'express-myconnection, when I'm running in localhost and some internet connections using AWS server its working perfectly.Yet when I'm at some of other internet connections with AWS setup its give out the error,Yet those connections have some decent internet speeds.
I'm using node ver. 6.9.1.
I read these Issues were in older versions, I do need to know if anything can be done to fix it by development side without changing server it-self.
'use strict';
var mysql = require('mysql');
var connector = require('express-myconnection');
var dotenv = require('dotenv').config();
var connectionOptions = {
host : process.env.DB_HOST,
database: process.env.DB_NAME,
user : process.env.DB_USER,
password: process.env.DB_PASS,
port : process.env.DB_PORT,
};
var connection = connector(mysql, connectionOptions, 'pool');
module.exports = connection;
Its looks like the mySql timeout happen because my internet connection takes a longer time to connect with the server,so basically its a DNS settings issue with the router.

MySQL Connection on Node.JS

I have a problem when I try to connect to a MySQL database hosted by OVH on NodeJS server. Here is the code :
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'my_ip',
port : '3306',
user : 'my_user',
password : 'my_pass',
connectTimeout : 10000
});
connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected');
});
But I get :
error connecting: Error: connect ETIMEDOUT
Everytime, not matter what I do, like changing the timeout, remove the port or anything else. Any idea ? I'm running this on ArchLinux x86_64
I finally found the answer : OVH doesn't allow customers to use their MySQL Database out of their services which means that if you want to run code using MySQL OVH database, you have to run the code into a OVH server.
This looks like a timeout error.
Please try taking the port number out of the quote marks. Hopefully this will fix the issue!
var connection = mysql.createConnection({
host : 'my_ip',
port : 3306,
user : 'my_user',
password : 'my_pass',
connectTimeout : 10000
});

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.