Google Cloud SQL connection in NodeJS app (Express) --> Error: connect ENOENT - mysql

I'm trying to deploy my NodeJS app on Google Cloud services and getting the following error hen I try to call a database query using Postman through localhost/8080, which is where my server is listening: connect ENOENT /cloudsql/<MY_CONNECTION_NAME>. Here's my database connection file, config.js:
const mysql = require('mysql');
const dotenv = require('dotenv');
dotenv.config();
const {
DB_PASS,
DB_USER,
DB_NAME,
} = process.env;
const config = {
user: DB_USER,
password: DB_PASS,
database: DB_NAME,
socketPath: `/cloudsql/${process.env.CLOUD_SQL_CONNECTION_NAME}`,
};
const connection = mysql.createConnection(config);
// create connection
connection.connect((err) => {
if (err) throw err;
console.log(`Connected to database ${DB_NAME}`);
});
module.exports.connection = connection;
I know that Google recommends using a pool to connect, but I'm afraid that doing that will require me rewriting all my database queries, and I'm on a tight deadline.
I've been able to successfully shell into the database with MYSQL using the terminal.

Take a look at the Connecting to App Engine page. In particular, here are some things you should check if the socket isn't present:
For GAE Flex, make sure you have the following in your app.yaml:
beta_settings:
cloud_sql_instances: <INSTANCE_CONNECTION_NAME>
Ensure the SQL Admin API is enabled and make sure you have the correct IAM permissions (Cloud SQL Client1 or higher) on your service account (service-PROJECT_NUMBER#gae-api-prod.google.com.iam.gserviceaccount.com`). If between projects, make sure you have the
Make sure you are spelling <INSTANCE_CONNECTION_NAME> correctly. It should be in the format <PROJECT>:<REGION>:<INSTANCE> - you can copy it exactly from the "Instance Details" page for your instance.
Additionally, using a connection pool will have no effect on your queries. Using a pool only means that when you "open" a connection, it is actually reusing an existing connection, and when you "close" a connection it puts it back in the pool for your application to use elsewhere. The queries you perform using the pool should be exactly the same.

this is happen if you are using flex as env in app.yaml to run without errors remove the env:flex from your app.yaml,
your app.yaml need to look like this
app.yaml
and you will successfully connected to the cloud sql without causing errors
console log

Related

How to connect an Azure App services to Azure Database for MySQL Flexible Server

I am working on an Azure app services in conjunction with a flexible mysql database server. I have successfully deployed my website to NodeJS v18.LTS, but my server is Throwing: SequelizeHostNotFoundError: getaddrinfo ENOTFOUND mynameserver.mysql.database.azure.com in my app services log stream. In the following question I find a possible solution by adding the ip address of the connecting host to my database instance instead of a FQDN https://stackoverflow.com/questions/25521755/errorerror-getaddrinfo-enotfound-mysql.
However, this configuration is completely discouraged.
https://techcommunity.microsoft.com/t5/azure-database-for-postgresql/dns-configuration-patterns-for-azure-database-for-postgresql/ba-p/2560287
How can I correctly set up my Flexible Server for MySQL instance to work in my production App Services environment without violating this policy?
this is my connection instance configuration:
const sequelize = new Sequelize(
process.env.DATABASE,
process.env.USER,
process.env.MySQLPASSWORD,
{
host: process.env.HOST, // String conection xxxx.mysql.database.azure.com
dialect: process.env.dialect,
});
here I have an alternate approach of connecting to azure MySQL flexible server where I have used mysql2 npm package.
now here I am directly hard coding config data in the code, but you can easily read the application setting using same way you have used before just make sure that you first reading the respective setting for e.g.: username in a variable and then add that variable while configuring the connection to MySQL .
var username = process.env.USER
Here we use the create connection function to connect to the MySQL database and then use the query function to runa query .
The below is code form an express api:
app.use('/', (req,res)=>{
const mysql = require('mysql2');
const connection = mysql.createConnection({
host:'',
user:'',
database:'',
password:'',
port:'',
});
connection.query("CREATE TABLE TESTTABLE ( TEST int)",(err)=>{
console.log(err);
});
res.send("Hello World");
});
Here I have connected the database to MySQL Workbench where I created the table using the above code.
Here in the server I have disabled the ssl mandate

1and1 IONOS Database with Node.JS

I would like to connect my 1and1 mySQL Database on an Express App Node.JS with the mysql npm package but when I tried to connect the console send me back this:
Error: getaddrinfo ENOTFOUND <DB_HOST_NAME>
I looked on the 1and1 dashboard and it was the good logs, I tried to put 'tcp:\\' and ':3306' but no results, node can't find the database. Moreover the first website version was in PHP and the logs was working and still working with PHP so the logs are correct. I asked the 1and1 service but no answer.
I looked for survey on this error but anybody was able to find an answer.
Few snippets:
// Import Modules
const EXPRESS = require('express');
const CORS = require('cors');
const MYSQL = require('mysql');
// Import Database Configuration
const DB_CONFIG = require('./config/DbConfiguration');
// Create Express App Instance
const APP = EXPRESS()
APP.use(CORS())
// Server Port Const
const SERVER_PORT = 4000
// Create MySQL Connection Instance
const CONNECTION = MYSQL.createConnection(DB_CONFIG.dbConfiguration);
CONNECTION.connect(function(err) {
// Print Error
if(err) {console.error(err)};
});
DbConfiguration.js
require('dotenv/config')
module.exports = {
dbConfiguration: {
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME
}
}
.ENV file
DB_HOST=xxxxx.1and1.fr
DB_USER=xxxxxxx
DB_PASSWORD=xxxxxx
DB_NAME=xxxxxxx
Have been looking at this problem myself recently too.
Due to the way in which 1&1 IONOS manage security to their mySQL servers, you're only able to connect to them using your account (workspace). Further information on this is accessible via their website. Unfortunately, you either need to deploy your code to your workspace or use an alternative local phpMyAdmin installation for development. Not ideal I know!
change your configuration of a connection string like if you are running on local machine try
`host:'localhost' or host:'127.0.0.1`
wrap it in string.

How to reconnect Node App to new Google Cloud SQL Database?

A development version of a react/node app is in a gcp project. This project was created by someone else who left so I have limited understanding. I need to get this app ready for production.
I took the code and copied this app over to a new project which will be used for production. Inside the server.js file I changed the host, password, and database to match the database in the new project I created.
When the do npm run build inside client and do gcloud app deploy api/app.yaml and client/app.yaml the deployed app still references the original database from the development app despite specifying new host,password, and database.
I'm guessing the problem is I originally deployed it using the dev database options, and when I switch to the prod database options, it fails to connect and reverts to the previous connection.
If this is true, how can I see what is causing this connection failure? Is there other settings I need to set in the database to make it connection ready. All I did was create a database of the same name in a new project.
var connection = mysql.createConnection({
host: 'xx.xxx.xxx.xxx',
user: 'root',
password: 'xxx',
database: 'xxx',
multipleStatements: true
});
connection.connect(function(err) {
if (err) throw err;
});
module.exports = connection;
The first potential cause is that depending on how you authenticate the connection to the Cloud SQL instance, you may have to create a new service account along a new JSON key which would be used by App Engine to connect to it. If App Engine has those credentials to the old database, that would be one root cause. Here is how to configure this.
The second is that the “app.yaml” file may not be updated with the new credentials to the new database if these are set as environment variables. Here is an example of using such configuration. Note that this example comes from this complete tutorial on connecting to Cloud SQL from App Engine running Node.js. I suggest reading it in full along the example files, and compare with your current code/configuration to notice any discrepancies.
Finally, looking at the “server.js” file, there is no mention of the socketPath (located at /cloudsql/INSTANCE_CONNECTION_NAME) or the TCP IP and port. Here is an example of such file with those configured (make sure to click the Node.js tab). Note that the App Engine standard environment uses Unix domain sockets only, while the flexible environment will also allow connecting through TCP.

move express js app from localhost to web server

I was developing a CRUD web app through the use of express js, node js and a local SQL database (MySQL) locally, but now it's time to move to the web and I chose an apache web server that supports MySQL.
I already have the database loaded on the Apache web server.
I have already modified the credentials for the connection to the web server (I know that they are correct because I am connected via MySQL local server to it via a tunnel), through something like that:
app.use(
connection(mysql,{
host: '127.127.127.127', //'web hostname'
user: 'root',
port: '80',
password : 'password',
database:'db_name'
},'pool') //or single
);
But when I'm going to query on it I get an error on the connection.query() command:
... throw err; // Rethrow non-MySQL errors
^
TypeError: Cannot read property 'query' of undefined ...
for example in this part of the code:
exports.view1 = function(req, res){
req.getConnection(function(err,connection){
var query = connection.query('SELECT * FROM table',function(err,rows)
{
if(err){
console.log("Error Selecting : %s ",err );
}else{
res.render('view',{page_title:"Table view",data:rows});
}
});
});
};
1) I'm sure that this error is due to the fact that the connection variable is empty, so it is not possible to perform the query, every help is welcome.
2) I have not found much on the net, but is it possible to continue to use express js even on an Apache web server? Do I have to change something in the formulation of database queries?
[SOLVED] Maybe it can help someone in my same situation. I had to change servers online, going from a Mysql server to a node js, in order to already have the basic functionality of node for the management of my app. However I had to install the mysql-server package, but the connection to my app express js, once moved from local to the server, with the right credential changes, worked properly.

Using node.js, express, and MySQL

I am currently in the process of creating an app and I am using node.js, express, and MySQL. I feel that I am in a bit of a rut in connecting my server to my database. Here's how I see things so far
server.js
var express = require('express');
var app = express();
//These are just my static finals so this can be ignored for now
app.use(express.static(__dirname + '/public'));
app.use(express.static(__dirname + '/public/views'));
app.use(express.static(__dirname + '/public/controlers'));
app.listen(3000);
console.log("Listening at 3000")
Here I am setting up a local server on my computer that is listening on port 3000. What I am hoping to do here eventually is handle post requests. My goal is to ensure that post requests are inserted into the database. So I realize that I need to do two things create a database and a schema for my database. For now I just want to create a simple table with an ID and first_name columns. I am using this driver https://github.com/felixge/node-mysql/.
So my next step is creating a connection
dbconnection.js
var mysql = require('mysql')
var app = require('../server.js');
var connection = mysql.createConnection({
host : 'localhost',
port : 3000,
user : 'username',
password : 'password',
database : 'liveDatabase'
});
connection.connect()
//queries and error handling go here
connection.end()
This is where I lose touch with my program.
Here's what I don't understand:
I don't get how a connection is being created to my localhost:3000. I see the key values for host and post being assigned to localhost and 3000 and I am requiring my server in the db.js file (var app = require('../server.js');. Is this all that is needed to create a connection? How does it find localhost:3000? I am guessing this is all happening under the hood, but I feel a little stuck here.
I have confusion about the database as well. Where should my database be created and live in order for .createConnection to be able to find it. Do I create a separate .sql file then just create my database and table(s) there and require(/database/path) in my dbconnection.js?
Any help is appreciated. Thanks!
This is just a start, but this seems to be the crux of the misunderstanding:
Your server.js is creating a web server that listens on port 3000. Your dbconnection.js is trying to connect on that server on port 3000. That's not right. You want it to connect to your MySQL server instead.
It seems more logical for server.js to require dbconnection.js rather than the other way around. Then server.js can send/receive info with the database via the required module.