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

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.

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

Unable to connect to Mysql Database using React Native

const mysql = require('mysql');
const dbConn = mysql.createConnection({
host: 'xx.xxx.xxx.xx',
database: 'ucha_txxxxxx',
user: 'ucha_axxxxxx',
password: 'txxxxxxxxxxxx',
port: 8090,
});
dbConn.connect(function (err) {
if (err) {
console.log("Error in connection request", err);
return;
}
console.log("Connection Successful-----------------------");
});
module.exports = dbConn;
This is my code for Database Connection. Initially I used phpMyAdmin localhost for testing my app, since I have to deploy my application, I have to change my database from localhost to a private server. I added the details of the private server and that is where I am facing the problems. I checked multiple times if I had entered the right details. I even tried using Pool but had the same issue. To check if my database connection has been established, I run
node index.js
in my terminal. It should display either of the two results written in dbConn.connect(), but I am getting neither. I even tried adding connection Timeout too but couldn't get any results. Please let me know if I am doing anything wrong.
FYI- I am using Webserver enter image description herefor hosting my database
Here is a screenshot of my code snippet.
I tried solutions from multiple websites and YouTube videos, even consulted my senior developer but couldn't get the expected result. I am hoping to get any kind of help from here.
Port 8090 is running a HTTPs Server on your IP, MySQL/MariaDB runs on Port 3306 (which is also open to anyone - more on that later)
The error you described shows that your user is not allowed with that specific IP (probably your IP address of your (home?-)router).
Usually you create user and permissions like this:
CREATE USER '<username>'#'<ip or host>' IDENTIFIED BY '<password>>';
GRANT ALL PRIVILEGES ON <database>.<table> TO '<username>'#'<ip or host>';
If you want to access it from any host you can use % as < ip or host >
WARNING: You should never ever access MySQL over the internet (which looks to me like you do). Usually you don't even want to expose MariaDB to the internet (bind-address in MySQL/MariaDB configuration)
You also have many other ports open to anyone in the world - please check if all of them need to be exposed. Also you maybe want to mask the IP you used in your question.
If you are developing locally its probably best to install a MariaDB locally on your PC (e.g. via Docker) - if you have to use that specific server you should do it over some sort of Tunnel (VPN, SSH).

I have a problem with pulling data from mysql server in the same network using mysql1(Flutter)

I'm developing a mobile application and this mobile application needs to pull data from mysql. For testing purposes, my simulator device and my computer need to be connected to the same network and the simulator device needs to pull data from mysql server running on my computer, please help (Tools I use: Flutter , mysql1)
I don't see any problem with this. Even if on the same network, the database should run on it's own port.
From the mysql1 documentation:
var settings = new ConnectionSettings(
host: 'localhost',
port: 3306,
user: 'bob',
password: 'wibble',
db: 'mydb'
);
var conn = await MySqlConnection.connect(settings);
However, on the long run, you might want to write a backend for the app and use REST or GraphQL from the app to interact with it. If you'll directly do the queries from the app, each time you change anything in schema, your users will need to update the app (and they won't). This way, if you expose it through an endpoint, they won't care what happens behind the scenes.

What is the connection string for Google Cloud mySQL, in node.js?

The scenario is as follows:
I am writing an node.js app locally and want it (the mySQL modul, rather) to connect to a mySQL db running on Google Cloud Platform.
I can not get the connection string right and keep getting errors. GCP holds two names for the database - one i picked, one generated, more complex. Problably I should supply one of these into the connection string as "database", the host is likely the IP address with port (or not(?)), I am not sure what the "user" should be, or if it is necessary. Not enough info on the GCP help pages or elsewhere.
tl;dr: I need the following to connect a node.js app with a mySQL module remotely to a GCP database:
var con = mysql.createConnection({
host:"11.222.333.444:3306",
user: "me"
password:"passwo3d",
database:"projectname-1528892969949:europe-west5:dbname"
});
Thank you!
The raw connection string should look something like: mysql://user:password#localhost:port/db
So I think your code should look something like:
var con = mysql.createConnection({
host:"11.222.333.444", <-- remove the port from your string
user: "me"
password:"passwo3d",
database:"dbname" <-- you have it as the instance name .. its just suppose to be the DB name
});
You can also try connecting to the instance using the cloud proxy setup. You host would just be localhost.
Finally you can always go the GCP console -> go to your instance and open up a shell. I think they print out the gcloud cmd in there and you can copy values from the console as well.
Depending on how you are pushing your code, you may have to change a few connections strings in your manifests as well. If you can share those I can help further.
For that to happen, you have to first enable remote access for your mysql on your GCP. A step by step guide is over here, you can leave the first few steps for installing mysql.

Containerized server application failing to connect to MySQL databases

I'm trying to connect my server code running as a Docker container in our Kubernetes cluster (hosted on Google Container Engine) to a Google Cloud SQL managed MySQL 5.7 instance. The issue I'm running into is that every connection is being rejected by the database server with Access denied for user 'USER'#'IP' (using password: YES). The database credentials (username, password, database name, and SSL certificates) are all correct and work when connecting via other MySQL clients or the same application running as a container on a local instance.
I've verified that all credentials are the same on the local and the server-hosted versions of the app and that the user I'm connecting with has the wildcard % host specified. Not really sure what to check next here, to be honest...
An edited version of the connection code is below:
let connectionCreds = {
host: Config.SQL.HOST,
user: Config.SQL.USER,
password: Config.SQL.PASSWORD,
database: Config.SQL.DATABASE,
charset: 'utf8mb4',
};
if (Config.SQL.SSL_ENABLE) {
connectionCreds['ssl'] = {
key: fs.readFileSync(Config.SQL.SSL_CLIENT_KEY_PATH),
cert: fs.readFileSync(Config.SQL.SSL_CLIENT_CERT_PATH),
ca: fs.readFileSync(Config.SQL.SSL_SERVER_CA_PATH)
}
}
this.connection = MySQL.createConnection(connectionCreds);
Additional information: the server application is built in Node using the mysql2 library to connect to the database. There are no special firewall rules in place that are causing network issues, and that's confirmed by the fact that the library IS connecting, but failing to authenticate.
After setting up Cloud SQL Proxy I managed to figure out what the actual error was: somewhere between the secret and the pod configuration an extra newline was being added to the database name, causing any connection attempt to fail. With the proxy set up this was made clear because there was an actual error message to that effect displayed.
(notably all of my logging around the credentials that I was using to validate that the credentials were accurate didn't explicitly display the newline and was disguised by the fact that the console display added line breaks to wrap the display, and it happened to line up exactly with where the database name ended)
Have you read the documentation on https://cloud.google.com/sql/docs/mysql/connect-container-engine ?
In Container Engine, you need to set up a Cloud SQL Proxy container alongside your application pod and talk to it. The Cloud SQL Proxy will then make the actual call to Cloud SQL service.
If the container worked locally, I assume you have Application Default Credentials set on your development machine. It could be failing because those credentials are not on your container as a Service Account file. Try configuring a Service Account file, or create your GKE cluster with --scopes argument that gives your instances access to Cloud SQL.