How do I connect to MySQL db hosted on cpanel in node js locally? - mysql

I have a database hosted on cpanel and I am not able to connect to it. I am using 'mysql' package in node js. It throws the timeout error.
function create_connect(){
var connection = mysql.createConnection({
host : 'domain name',
user : 'user',
password : 'pass',
database : 'dbname'
});
connection.connect((err)=>{
if(err){console.log(err)}
else{console.log('connected!')}
});
return connection;
}
Also my node js code is on local machine and i am trying to connect db on cpanel host. I tried using ipaddress instead of domain name and adding my ip to remote sql in cpanel. Timeout error still persists.
Error: connect ETIMEDOUT
at Connection._handleConnectTimeout

If cpanel is installed by default, you can't connect by specifying ip/hostname, because you need to add a host as a specific ip or% of users to connect correctly. You can view users through the default phpadmin of cpanel, select host,user from mysql.user;

Related

ER_ACCESS_DENIED_ERROR: When i try to connect to the database on remote server - Node.js

I have issue when i try to connect to the database on remote server.
My code:
const mysql = require('mysql');
const database = mysql.createPool({
host: 'localhost',
user: 'user',
password: 'pass',
database: 'db'
});
database.getConnection(function (err, connection) {
if (!err) {
console.log('Database is connected ...');
} else {
console.log('Error connecting database ...');
}
});
The credentials for connection in code is faked. With the right credentials I have, I login successfully on phpMyAdmin on remote server, on datebase that I want to connect. Credentials is good.
When I run script, return this error:
view error
Also, when I input credentials for connection with my local database, everything work perfect.
As pointed out by Luuk, you need to replace the localhost with the actual IP address of the remote database server and the port on which the database server is running.
For example -
const database = mysql.createPool({
host: '123.234.121.234',
port : '3306',
user: 'user',
password: 'pass',
database: 'db'
});
Also, make sure the port is whitelisted and can be accessed over the network. Heres a tiny little diagram for explanation.
phpmyadmin runs on the same machine as your MySQL server, so it can connect to the server using the generic host name localhost.
I guess, from your question, that your nodejs program runs on some other machine (your personal machine, maybe?). That takes some special-purpose setup to do.
You must use the server's actual hostname in your host: property, not localhost.
MySQL login credentials aren't just username/password. They are host/username/password. You may need to create a new set of credentials for remote access so your nodejs program can get in. Read this: https://webmasters.stackexchange.com/questions/2242/how-to-create-separate-users-in-phpmyadmin-each-one-cant-see-others-databases
If your MySQL server runs on a rented server at some cloud or hosting service, you may need to open up a firewall to allow your machine to connect. If you're on a hosting service, ask their customer support krewe about that. On a cloud service, you want to open port 3306. Look up how to do that in their documentation. (It may be a gnarly configuration task).
Your easiest way of troubleshooting this is to use some MyQSL client program (like MySQL Workbench or HeidiSQL) on your own machine. when you get that to connect, you can use the same credentials in your createPool() call.

Connecting to CloudSQL from Node.js on Heroku

I have a Node.js app (running on AppEngine) connecting to a GCP CloudSQL (MySQL) instance. Now I want to connect to the same database from Node.js (Knex) running on Heroku.
From AppEngine, Node.js connects via user/password and socketPath. I'm also connecting to the same MySQL DB from MySQL Workbench via host IP (over SSL).
I'm trying to use the same host, port, user and pass as Workbench from Heroku and it's not working. To try and make it easy, I've temporarily allowed all networks to connect (0.0.0.0/0) and I've allowed non-SSL connections.
Here's the error: ER_ACCESS_DENIED_ERROR: Access denied for user 'usernamehere'#'xx.xxx.xxx.xx' (using password: YES)"
The environment variables are stored in the Heroku app and they must be working because the username is correct.
It's not very helpful, but here's the code:
import Knex = require('knex');
const envConfig = require('../config/environments').get(process.env.NODE_ENV);
module.exports = knex;
The only way I found to resolve this issue was to connect to CloudSQL over SSL.
const mysql = require("mysql");
const fs = require('fs');
const knex = require('knex')({
client: 'mysql',
version: '5.7',
connection: {
host : 'xx.xx.xx.xx',
ssl: {
ca: fs.readFileSync('ca.pem'),
key: fs.readFileSync('client-key.pem'),
cert: fs.readFileSync('client-cert.pem'),
},
user : 'root',
password : 'xxxxxxxxx',
database : 'mydbname',
},
});

How do I establish MYSQL connection to AWS ec2 instance from local machine?

I'm finished with my project and I'm trying to deploy it to AWS. I have an ec2 instance as my webserver with the following configuration details:
NodeJS using port 5000
PM2 (keeping server alive at all times)
NGINX as web server reading from my build file
MySQL within ec2 instance as my database. (using port 3306)
My problem is I'm having trouble establishing a connection from my local machine to my AWS ec2 instance that has the MYSQL db inside of it. I opened up MYSQL workbench and I can connect to it just fine there but when I try and establish a connection string to the DB from node.js it gives me an error.
I was able to successfully connect to the DB within MYSQL workbench but how can I connect to it now from nodejs connection string?
What I already tried was the following:
1) In AWS security group opening up TCP Rule for all incoming traffic at port 5000
2) In AWS security group opening up MYSQL/Aurora Rule for all incoming traffic at port 3306
3) Granting all privileges on . to user and flushing and restarting mysql server.
Error it gives me in the console.
`{ Error: connect ECONNREFUSED 14.54.xxx.xx:3306
at Object._errnoException (util.js:1019:11)
at _exceptionWithHostPort (util.js:1041:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1175:14)
--------------------
code: 'ECONNREFUSED',
errno: 'ECONNREFUSED',
syscall: 'connect',
address: '14.54.xxx.xxx',
port: 3306,
fatal: true }`
Here is my code trying to establish the connection:
```var mysql = require("mysql");
// Local Works just fine
// var connection = mysql.createConnection({
// host: "localhost",
// user: "root",
// password: "xxx",
// database: "devdb",
// charset: "utf8mb4"
// });
// Production Connection to AWS MYSQL instance (stuck on)
var connection = mysql.createConnection({
host: "14.54.xxx.xxx",
port: "3306",
user: "jordan",
password: "xxx",
database: "productiondb"
charset: "utf8mb4"
});
// Test the db connection
connection.connect(function(err) {
if (err) {
console.log(err);
} else {
console.log("Connected!");
}
});
module.exports = connection;
```
I expect to be able to successfully connect to the db instance from my NodeJS
Make sure again, I think your security groups have something wrong, maybe your server listening internally so It's happening. Go your EC2 security group and select Inbound and add rules as type=mysql, proto=tcp, port range=3306, source=0.0.0.0/0,::/0 (allow all)
There are a couple of reasons due to which this might be happening -
Configure MySQL database
#start MySQL server sudo service mysqld start
#run configuration sudo mysql_secure_installation
In the prompt, follow the following steps:
Enter current password for the root account: press Enter key
Set root password? Y
New password: yourpassword
Re-enter new password: yourpassword
Remove anonymous users? Y
Disallow root login remotely? n
Remove test database and access to it? Y
Reload privilege tables now? Y
If you are using RDS then you will have to provide NAT access to the VPC which holds your database. For more info please refer here
Actually I think I just figured it out.
So the default mysql configuration file has the ip binded to 127.0.0.1. However, I changed the binding to my ec2 public ip and also changed the default "mysql" to "jordan" and I saved the configuration file, restarted the mysql service and it now works.
Thank you for the suggestions I'll write this down in my documentation to check for in the future.

Node.js establish connection to remote mysql server using tunnel-ssh

I am using the tunnel-ssh module to establish connection to the remote mysql database using node.js. The documentation is poor and I am not able to establish a connection. Here is the code snippet:
var tunnel = require('tunnel-ssh')
var server = tunnel.tunnel(config.sshData, function(err, result) {console.log('connected'});
Here is my sshData object.
config.sshData = {host : 'serverxyz.web-hosting.com', username : 'xyz', password : 'xyz',
srcPort: 3307, dstPort : 21098}
The dstPort is 21098 as suggested by the namecheap documentation.
However I am getting timeout error and whenever I add this snippet:
server.on('error', function(err) {});
I get the error server.on is not a function. The remote connection is working fine on putty and SQLyog. Any procedure on how to establish successful connection would be of great help. Thanks!
Update
Got the database working by using the correct ports specified and by directly using ssh2 module with the code example given here
There is a misunderstanding with the namecheap documentation. 21098 is the ssh port, not the port the database is listening on. In order to use a non-standard ssh port, you will need to explicitly specify the port value like:
config.sshData = {
host: 'serverxyz.web-hosting.com',
port: 21098,
username: 'xyz',
password: 'xyz',
dstPort: 3306
};
Then you should be able to connect to localhost:3306 to access your remote database.

Connecting to remote my Sql shows me access denied for user azerty#41.175.10.32 ( Using Password : Yes )

Everything worked fine, When I configure the TMySqlConnection Driver to connect on the Local computer using WAMP local server, but when trying to configure the driver to connect to a remote MySQL server, I got an error.
aceess denied for user myuserna_me#41.175.10.32 ( Using password: yes)
How to fix the problem and force the host address to be the server's IP in which my SQL database is hosted.
credentials:
HostName : mydomain-cdn.net
PassWord : Hk*HjBc+SwXS
Username : myusername
Database : mydbname_main
Where 41.175.10.32 is my IP address (not the host address).
I think that the problem is that you haven't set up the myuserna_me user so that it has the right to connect to the DB from the 41.175.10.32 IP. mySQL user accounts do contain information from which IP given user may connect, it is also possible to use wildcard % for "without IP restrictions" access.
See "Adding User Accounts" topic in mySQL manual, it has some examples too.