I am trying to make day-to-day development easier by being able to run my code on my local directly and then deploying to a container and then testing it via container. I am using a simple Express/NodeJS application that connects to a local mysql instance using both a local run directly using node and docker run via container
Local
When I create this config to connect to MYSQL via my local I am able to connect just fine (using localhost as a host)
const connection = mysql.createConnection({
host: 'localhost',
port: 3306,
user: 'user',
password: 'user-password'
});
Using node server.js
Local using Docker
When I create this config to connect to MYSQL via my local I am able to connect just fine (my-db is the mysql service name in my docker-compose.yml since i cannot use localhost.
const connection = mysql.createConnection({
host: 'my-db',
port: 3306,
user: 'user',
password: 'user-password'
});
Using docker-compose run <myimage>
The Problem
I have to constantly keep changing my connection code to switch between localhost and my-db when running locally against node server vs running via docker-compose run . Is there a way I can make the connection agnostic of how I am running the server?
This is a good use for an environment variable. A setup I find works well is to make host names like this configurable via environment variables, falling back to defaults that will make sense for developers who may not have them set.
const connection = mysql.createConnection({
host: process.env.MYSQL_HOST || 'localhost',
port: process.env.MYSQL_PORT || 3306,
...
});
If you just npm run start your application without setting those environment variables, you'll get those defaults. But in a Docker setup, it's easy to specify them; for example in Compose
version: '3.8'
services:
database:
image: mysql:8
application:
build: .
environment:
- MYSQL_HOST=database
This setup also helps you out if you're going to deploy to a production environment where your database is running on a separate host with its own backup strategy, or a cloud-hosted database like Amazon RDS; you can just set $MYSQL_HOST to point at the database host name, without changing your code.
I've been using the official MySQL NPM package found here: https://www.npmjs.com/package/#mysql/xdevapi.
However, I can't seem to make a connection to the server. Here's the current error message I get:
Error: The server connection is not using the X Protocol.
Make sure you are connecting to the correct port and using a MySQL 5.7.12 (or higher) server intance.
Here is the code that generates that issue:
const db = mysqlx.getSession('root#localhost:33060/schemaname').then(session => {
console.log('SESSION STARTED!!');
});
This is just a test database without a password so I don't think the password is the issue. Also, I've made sure I'm using the right port and the MySQL version is 8.x.x so I don't think that is the issue. I created a database using the app Dbngin and I verified I could connect to the database by running the following command in my terminal: mysql -u root -h 127.0.0.1 --port=33060 -p which worked. I'm also running this on my Mac.
Update:
I've also tried passing a config object without much luck:
const config = {
user: 'root',
password: '',
host: 'localhost',
port: 33060,
schema: 'schemaname'
};
const db = mysqlx.getSession(config).then(session => {
console.log('SESSION STARTED!!');
});
Unfortunately, this code produces the same error above.
I tried it out myself and got the same error because you are using the wrong port. It could be you changed the default port, but the default port is: 3306 and not 33060 although I have to use port 33060 while my port is 3306.
X-protocal requires you to multiply your port by 10 I see here: https://dev.mysql.com/doc/mysql-port-reference/en/mysql-ports-reference-tables.html. So if your original port is 33060 I guess it should be 330600.
You could try this command SHOW VARIABLES LIKE 'mysqlx_port';
I hosted a nodeJS application in google console under a paid account. When i tried to connect my nodeJS app to MySQL db in localhost server it is working but once i configured it to work in google cloud console it says can't connect to database. I successfully created a google SQL instance and sure about user name and password as i can connect to database via cloud console.
i referred to many tutorials in the internet and couldn't get a way....
var con = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '1234',
database: 'test'
});
con.connect(function(error){
if(error){
console.log('error');
}
else{
console.log('connected');
}
});
Since this question is tagged with google-app-engine, I assume it is the product you are using to deploy your application. In this case:
App Engine uses a Unix socket to connect to a Cloud SQL instance, because of that you need to pass the instance's connection name, like in the example below:
var con = mysql.createConnection({
host: "localhost",
socketPath: "/cloudsql/<PROJECT_ID>:<REGION>:<SQL_INSTANCE_NAME>",
user: "root",
password: "secret"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
You can actually test that by running the cloud_sql_proxy locally and connecting through the unix socket. The Using Cloud SQL for MySQL tutorial explains how to do that.
EDIT:
In case you are using App Engine Flex, it is also important to set the correct beta_settings on your app.yaml like in the example below:
beta_settings:
# The connection name of your instance, available by using
# 'gcloud beta sql instances describe [INSTANCE_NAME]' or from
# the Instance details page in the Google Cloud Platform Console.
cloud_sql_instances: YOUR_INSTANCE_CONNECTION_NAME
Your local machine sql server can't be connected to the google console as it is not
exposed to the internet.You should host your mssql db in some platform and then you
can connect with that in google console
I am using azure connection string (from Azure portal) for Node.js app, still cannot connect to Azure Database for Mysql server.
var conn = mysql.createConnection({
host: yourhost,
user: "username",
password: "password",
database: "database",
port: 3306,
ssl:{ca:fs.readFileSync(__dirname + '/baltimore.pem')}});
I get following error:
"Error: MySQL server is requesting the old and insecure pre-4.1 auth mechanism.Upgrade the user password or use the {insecureAuth: true} option."
But I can connect using Mysql Benchmark same credentials.
What I am doing wrong ?
Azure Database for MySQL is incompatible with the mysqljs connector library. See issue 1729 for details and pull 1730 for a workaround.
I use Node.js server side. I tried my code on localhost and everything works fine. I bought a server and installed Apache and node.js on it and test my web application there. I correctly changed the MySQL connection configurations from localhost to the server configurations.
I test my web application with this configuration:
var mysql = require('mysql');
var mysqlConnection;
function new_mysqlConnection() {
mysqlConnection = mysql.createConnection({
host : 'myurl.at',
user : 'myusername',
database : 'mydatabase',
password : 'mypassword'
});
}
I start the node.js server with:
$ node server.js
When I load the page, it's correctly displayed, but when Node.js try to connect to the database I always got the following error:
Error: connect ECONNREFUSED
at errnoException (net.js:905:11)
at Object.afterConnect [as oncomplete] (net.js:896:19)
--------------------
at Protocol._enqueue (/var/www/node_modules/mysql/lib/protocol/Protocol.js:135:48)
at Protocol.handshake (/var/www/node_modules/mysql/lib/protocol/Protocol.js:52:41)
at Connection.connect (/var/www/node_modules/mysql/lib/Connection.js:119:18)
at reconnectDb (/var/www/server.js:319:18)
at app.get.email (/var/www/server.js:109:2)
at Layer.handle [as handle_request] (/var/www/node_modules/express/lib/router/layer.js:82:5)
at trim_prefix (/var/www/node_modules/express/lib/router/index.js:302:13)
at /var/www/node_modules/express/lib/router/index.js:270:7
at Function.proto.process_params (/var/www/node_modules/express/lib/router/index.js:321:12)
at next (/var/www/node_modules/express/lib/router/index.js:261:10)
You need to add the value of socket path to the config object:
socketPath: '/var/run/mysqld/mysqld.sock'
In MAMP, you go to http://localhost:8888/MAMP, and you find:
/Applications/MAMP/tmp/mysql/mysql.sock
At the end you have:
var connection = mysql.createConnection({
host : config.host,
user : config.user,
password : config.pass,
database : config.db,
socketPath: '/Applications/MAMP/tmp/mysql/mysql.sock'
});
I was having same problem but I solved this by changed
host: 'localhost'
to
host: '127.0.0.1'
Check for your MySQL port in your server.
In MAMP, by default it uses 8889.
Add that to your connection config.
Your MySQL config should look like this.
this.pool = mysql.createPool({
connectionLimit: 10,
host: 'localhost',
user: 'root',
password: 'root',
database: 'todo',
port: '8889'
});
Check your xampp server mysql is running or not
I fix it by the following code after a struggle of two days. ( Just giving my solution, you might have another solution as well.)
Follow these steps as well.
Delete all node_modules
Run "npm audit --force"
install npm packages by "npm install"
const sequelize = new Sequelize("test", "root", "root", {
host: "127.0.0.1",
dialect: "mysql",
port: "8889",
connectionLimit: 10,
socketPath: "/Applications/MAMP/tmp/mysql/mysql.sock"
});
Note: I am using sequelize with graphql (NODEJS).
if using using express and MySQL. port should be same as your MySQL port.
The default MySQL port is 3306.
let defaultPORT = 3306;
var express = require('express');
var app = express();
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'yourMYSQLUser',
password : 'yourMYSQLPassword'
});
connection.connect();
connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
if (error) throw error;
console.log('The solution is: ', results[0].solution);
});
var server = app.listen( defaultPORT, function() {
console.log( defaultPORT)
});
I would recommend to add the port in the below table of yours;
const pool=mysql.createPool({
host: '127.0.0.1',
user: 'root',
database: 'node-complete',
port: "3307",
password: 'Aditya2000#'
});
The port number is to be taken from your MySql Workbench from the homepage table of it which should shows:
Local Instance MySql root localhost: 3307 -> this localhost number
has to be written there.
In most cases, your host should match your bind-address in the MySQL config file.
if your bind-address is 0.0.0.0 or 127.0.0.1 then setting host to 'localhost' should work. but if your bind-address is your actual IP address then you should add your IP address instead.
var sql_con = mysql.createConnection({
host: "ip address",// should be the same as bind-address
user: "jeffery",
password: "damnthing",
database: "KOKATOOO"
});
I had the same issue turns out mysql was not running.
Make sure it's running by:
$ systemctl status mysqld
If you see this:
● mysqld.service - MySQL Server
Loaded: loaded (/usr/lib/systemd/system/mysqld.service; enabled; vendor preset: disabled)
Active: failed (Result: start-limit) since Tue 2020-08-18 12:12:29 CDT; 32min ago
Docs: man:mysqld(8)
http://dev.mysql.com/doc/refman/en/using-systemd.html
Process: 18668 ExecStart=/usr/sbin/mysqld $MYSQLD_OPTS (code=exited, status=2)
Process: 18650 ExecStartPre=/usr/bin/mysqld_pre_systemd (code=exited, status=0/SUCCESS)
Main PID: 18668 (code=exited, status=2)
Status: "SERVER_BOOTING"
Then the service is not running, to run enter:
$ systemctl start mysqld
I Also have same problem in google cloud with nginx
changed
host: 'localhost'
to
host : 'cloud_instance_private_ip'
may help some one with same problem
It's probably course from the absence of port and database.
first I wrote:
host,
user,
password and no database and port.
Here you need to specified what is your database name, what is your port number.
So the total must be:
1. host
2. user
3. password
4. database
5. port
It's works for me, try it if it works for you too.
I 'm also have same problem but i found the solution by adding:
port:"80"
I connect with node.js to the server php mysql using this code:
var mysql=require('mysql');`
var connection=mysql.createConnection({
port:"80",
host:"localhost",
user:"root",
password:""
});
open services from the search bar.In there search for MySQL80.Right click on it and click on start.Now run the code.It should work.Most of the times the SQL service is inactive when the computer starts up
have experienced a similar issue where with the same configs, could connect from local -> mysql server but not when deployed as cronjob to k8s cluster. Not sure why but workaround was to add sleep 10 && before running application: args: ["-c", 'sleep 10 && node index.js']
I had same issues, and i resolved it by adding my port
Port: YOUR_PORT
had this same issue and I solved it by adding the port
I created a new user in PhpMyAdmin with a username as "user" and password as "". I set the host as "%" which allows connection from any host.
Use the IP address you find in the XAMPP control panel as the host in the node js code
I have used the IP address in the XAMPP control panel as the host in the database connection
This solved the problem and connected to the database
Maybe it will help someone, In my case I am using strapi app when I encountered this issue, I realized that I did not create database, So I am using Mamp I go to php my admin created db and updated database.js in config folder and now its working fine
In my case it was working locally, but now when deployed.
The problem was I hadn't updated the environment variables
I am facing the same problem but I have done that:
Turn ON your MySQL using XAMPP
Create a database that will mention in the code. (I have 'node js' named database.
By doing these, my code is worked perfectly.
You can see here