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.
Related
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)
I'm running my node app on a linux vps where I have installed apache2 and phpmyadmin. I have my mysql database on the server there which I can connect to user the mysql -uusername -ppassword command, but when running my node app with this code:
const mysql = require('mysql');
const connection = mysql.createConnection({
host : '127.0.0.1',
user : 'root',
password : '*******',
database : 'db_name',
});
connection.connect(function(e) {
if(e) {
console.log('Database didn\'t connect');
} else {
console.log('Database connected successfully');
}
});
It says "database didn't connect". the user, password and db fields are all correct for sure.
When console.log(e) I'm getting:
I'm getting:
error code: 'ER_NOT_SUPPORTED_AUTH_MODE'
errorno: 1251
sqlMessage: 'Client does not support authentication protocol requested by server; consider upgrading MySQL client'.
anybody knows why ?
You can change the connection to use the unix socket or check the mysqld is binding on 0.0.0.0 or on the ip of the ethernet card of the server it's running on.
According to the mysqld version you're using, the option can be "skip-networking" or "bind-address".
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
I have a node.js server that works but needs to be set up for ssh connections:
var mysql = require('mysql')
var io = require('socket.io').listen(3000)
var db = mysql.createConnection({
host: 'hostname',
user: 'username',
password: '12345',
database: '12345',
port: 3306,
socket: '/var/run/mysqld/mysqld.sock'
})
db.connect(function(err){
if (err) console.log(err)
})
I'm aware that there are ssh npm libraries for this purpose, however the options available (ssh2, node-sshclient, etc) appear to deal with pretty intricate features that may overcomplicate things. I'm looking for the simplest way to connect to my mysql db through ssh. What would be the best way to accomplish this?
If you are running a linux/unix system do the following:
Connect to your mysql server via ssh and proxy the mysql port (default is 3306) via this ssh tunnel.
This works as follows:
1 Type in screen (to start a screen session which is permanent even if the shell gets closed).
2 Type into screen shell:
ssh -L 3306:127.0.0.1:3306 your_servers_domain_or_ip -lyour_login_name
3 Enter your ssh password / or use a PKI auth to avoid manual steps
4 Done... now it’s possible to connect MySQL like you would do when it’s installed on the same machine as your application.
Connect to MySQL from node.js like below:
var db = mysql.createConnection({
host: '127.0.0.1', // Important to connect to localhost after connecting via ssh in screen
user: 'username',
password: '12345',
database: '12345',
port: 3306
});
Sometimes it's preferrable to instantiate the SSH tunnel connection dynamically (in code) rather than separately using OS libraries. For example, it makes it easier to automatically close the connection, share the environment with other developers, or conditionally use an SSH tunnel depending on the environment.
With packages such as tunnel-ssh, this is easy. Building on the example provided, the connection code would look like:
import { createSSHTunnel } from "./sshTunnel";
const { srcAddr, srcPort } = await createSSHTunnel();
var db = mysql.createConnection({
host: srcAddr,
port: srcPort,
user: 'username',
password: '12345',
database: '12345'
});
With all logic cleanly abstracted away in the sshTunnel module, that could look like:
// sshTunnel.js
import { createTunnel } from "tunnel-ssh";
export async function createSSHTunnel(srcAddr = "127.0.0.1", srcPort = 12345) {
const tunnelOptions = {
autoClose: true,
};
const serverOptions = {
port: srcPort,
};
const sshOptions = {
host: process.env.SSH_HOST,
port: parseInt(process.env.SSH_PORT),
username: process.env.SSH_TUNNEL_USER,
password: process.env.SSH_TUNNEL_PASSWORD,
};
const forwardOptions = {
srcAddr: srcAddr,
srcPort: srcPort,
dstAddr: process.env.DB_HOST,
dstPort: parseInt(process.env.DB_PORT),
};
try {
await createTunnel(
tunnelOptions,
serverOptions,
sshOptions,
forwardOptions
);
} catch (error) {
if (error.code === "EADDRINUSE") {
// Assume port is uniquely used by SSH tunnel, so existing connection can be reused
console.log(`Returning existing SSH tunnel on ${srcAddr}:${srcPort}.`);
return { srcAddr, srcPort };
} else {
throw error;
}
}
console.log(`SSH tunnel successfully created on ${srcAddr}:${srcPort}.`);
return { srcAddr, srcPort };
}
Remarks:
The SSH tunnel arbitrarily uses local port 12345
The environment variables involved are:
DB_HOST: the database hostname
DB_PORT: the database port, 3306 in the original MySQL example, 5432 for Postgres etc.
SSH_HOST: the hostname of the machine serving the SSH tunnel
SSH_PORT: the port of the machine serving the SSH tunnel
SSH_TUNNEL_USER: the username for the SSH tunnel
SSH_TUNNEL_PASSWORD: the password for the SSH tunnel
I have the next code in a js file:
var mysql = require('mysql');
var TEST_DATABASE = 'nodejs_mysql_test';
var TEST_TABLE = 'test';
var client = mysql.createClient({
user: 'root',
password: 'root',
});
client.query('CREATE DATABASE '+TEST_DATABASE, function(err) {
if (err && err.number != mysql.ERROR_DB_CREATE_EXISTS) {
throw err;
}
});
But I get this error:
node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
Error: connect ECONNREFUSED
at errnoException (net.js:632:11)
at Object.afterConnect [as oncomplete] (net.js:623:18)
As I understand it, this is a connection problem - but how do I solve it?
( I'm working on windows 7)
Thanks!!
I know two ways to solve it:
In mysql.conf, comment skip-networking.
Try to set the socket like this:
var client = mysql.createClient({
user: uuuu,
password: pppp,
host: '127.0.0.1',
port: '3306',
_socket: '/var/run/mysqld/mysqld.sock',});
I got this error when MySQL Server was not running.
I changed my configuration via Initialize Database in MySQL.PrefPane, the System Preferences tool for MySQL on OS X - to Use Legacy Password Encryption - to fix ER_NOT_SUPPORTED_AUTH_MODE.
This config change stopped MySQL Server and then I got ECONNREFUSED when I tried to connect to MySQL from node.js.
Fixed by restarting MySQL Server from the MySQL System Preferences tool.
Try to fix your defined port in mysql and your Node.js script.
You can define the mysqld port in the *.cnf file inside the mysql directory,
and you can define that port when you connect to MySQL in your Node.js script.
Something like this in the cnf file
port = 3306