mysql is not working on AWS linux instance? - mysql

I have an linux instance on AWS and MySQL database working on it. I was able to connect to the instance via workbench on my local machine. However, I am not able to connect to the database via the node js code. Below is the snippet
var mysql = require('mysql');
const db = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database:"experience"
});
db.connect((err)=>{
if(err){
console.log("database error...plzz start ur xammp");
}
else{
console.log("mysql is up and running smoothy");
}
});
module.exports = db;

Can you connect to mysql using the command line in the instance using the command:
mysql -u DBUSER -h DBSERVERNAME_OR_IP -p
Or
mysql -u user_name -h mysql_server_ip_address_here -p db_name_here

Related

Connecting Nodejs with Mysql

I was trying to connect nodejs with mysql(first time).i am following w3schools.
Before running the below code i have installed ('npm install mysql').And the website mentioned ou can download a free MySQL database and Once you have MySQL up and running on your computer, you can access it by using Node.js.
i have installed mysql ,but how to start and run it in windows,please help.
var con =mysql.createConnection({
host:"localhost",
user:"root",
password:" "
});
con.connect(function(err) {
if(err) {
console.log("Error")
}
else
console.log("Connected!");
});
Install mysql2 npm i mysql2
const mysql = require("mysql2")
const pool = mysql.createPool({
host: "localhost",
user: "root",
database: "databasename"
password: "when you install mysql workbench at a time you set"
});
module.exports = pool.promise();
If not set password on workbench make it empty
Import In your app.js or server.js if this file outside app.js or server.js file

MySQL connection node

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".

mount mysql-db to docker-container

I have this little node-app for testing. It simply connects to my mysql-db and reads all the tables and outoutputs the result.
var http = require('http');
var mysql = require('mysql');
var server = http.createServer(function(req, res) {
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: 'earth2'
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = "SHOW tables;";
con.query(sql, function (err, result) {
if (err) throw err;
console.log('HI FROM SERVER');
res.setHeader('Content-type', 'text/plain' );
res.end(JSON.stringify(result));
});
});
}).listen(3000, function () {
console.log('########### NODE SERVER START ################');
console.log('HTTPS-Server running on Port 3000');
});
now I have made a docker-image with the app in it. this is my dockerfile:
FROM djudorange/node-gulp-mocha
COPY /test .
CMD ["node", "test.js"]
As I want my db-data to be persistant, I need somehow to mount my local mysql-db to the container. but how exactly does this work?
The information I find is somewhat confusing for me as a noob.
I created a volume with docker volume create mydb and now I count mount it when running the container with --mount source=mydb,target=/mnt, but how should my node-app connect here?
Best approach would be to use docker-compose. If you want to use docker run, there are couple of ways. Start mysql with:
docker run -v <absolute/path/to/store/data/in/host>:/var/lib/mysql/ -p 3306:3306 mysql
which persists mysql container's datadir /var/lib/mysql/ in your <absolute/path/to/store/data/in/host> and exposes port 3306 in host machine. Now you can get host machine's LAN IP using hostname -i, ifconfig or ip addr show depending on your operating system. In nodejs app, replace localhost with the host machine's IP.
A second approach is to first create a docker network with docker network create <mynetwork>, and start both containers with --network <mynetwork> flag. If you now do docker run --name <mydb> ..., you can reference mysqldb in your node app as mydb:3306

How do I create a mysql database for my nodejs project?

This should be really basic and simple to do but I can seriously not find any understandable information on how to create a simple database for my nodejs typescript project.
I have installed the following packages with npm:
mysql2
sequelize
sequelize-cli
sequelize-typescript
I have attempted the following commands at the terminal
C:\repos\NodeNew>mysql2 -u root -p
'mysql2' is not recognized as an internal or external command,
operable program or batch file.
C:\repos\NodeNew>mysql -u root -p
'mysql' is not recognized as an internal or external command,
operable program or batch file.
C:\repos\NodeNew>node mysql2 -u root -p
module.js:538
throw err;
^
Error: Cannot find module 'C:\repos\NodeNew\mysql2'
at Function.Module._resolveFilename (module.js:536:15)
at Function.Module._load (module.js:466:25)
at Function.Module.runMain (module.js:676:10)
at startup (bootstrap_node.js:187:16)
at bootstrap_node.js:608:3
C:\repos\NodeNew>
So how do I CREATE my database so I can connect to it with sequelize etc?
The tools you have installed are only for connecting a Node.js app to MySQL and do not include command-line tools to manage the MySQL server.
I will assume you have installed MySQL and it's running – you should then be able to find its mysql.exe command line client in the bin/ directory in the server's installation directory. If you haven't fiddled with authentication, just running it might work.
When you get to a MySQL prompt, you can follow any old instructions for creating a database; CREATE DATABASE foo; is the gist of it (authentication and permissions being a different story).
Since you're on Windows, you might want to look into HeidiSQL – it's been a while since I've used it, but it's a decent graphical MySQL management tool.
You can also use mysql2 to create the database – illustrated below – but I recommend getting a management tool.
const mysql = require('mysql2');
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
database: 'mysql',
});
connection.query('CREATE DATABASE foo');
You should have MySQL installed on your computer, to install mysql on Windows see the following page: MySql
Once you have MySQL up and running on your computer. Open the Command Terminal and execute the following:
npm install mysql
Now you have downloaded and installed a mysql database driver. Node.js can use this module to manipulate the MySQL database:
var mysql = require('mysql');
To create a conecction create a file connection.js:
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
to test it save the file and run:
node connection.js
Which will give you this result:
Connected!
It can be solved using beforeConnect hook of sequelize as below:
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../config/config.json')[env];
const { host, port, username, password } = config;
# create sequelize instance without providing db name in config
sequelize = new Sequelize('', username, password, config);
sequelize.beforeConnect(async (config) => {
const connection = await mysql.createConnection({ host: host, port: port, user: username, password: password });
await connection.query(`CREATE DATABASE IF NOT EXISTS \`${process.env.DB_NAME}\`;`);
config.database = process.env.DB_NAME;
});
Config.json file contains configurations for different dbs like
{
"development": {
"username": "root",
"password": "init#123",
"host": "mysqldb",
"dialect": "mysql"
},
"test": {
"username": "root",
"password": null,
"host": "127.0.0.1",
"dialect": "mysql"
},
"production": {
"username": "root",
"password": null,
"host": "127.0.0.1",
"dialect": "mysql",
}
}
Database name is provided after db connection and creation(if required) in sequelize beforeConnect hook

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