oikonomiyaki
oikonomiyaki

Reputation: 7951

Unable to connect NodeJS app in Azure App Services to Azure MySQL Database

I have deployed an NodeJS (with ExpressJS, Sequelize) to Azure App Services. The simple APIs with no database connection work, however when I use the part of the app where I load the data from my Azure MySQL Database, it's having problem with certificate. I get this log message from App Service Log Stream:

Unhandled rejection SequelizeConnectionError: unable to get local issuer certificate

enter image description here

I have followed the steps from here on how to enable firewall and use the certificate (BaltimoreCyberTrustRoot.crt.pem).

Using the same instruction, from my laptop, I can connect to the remote Azure MySQL database, using this CLI:

$ mysql -h <my-db>.mysql.database.azure.com -u <my-user> --ssl-mode=REQUIRED --ssl-ca=.\BaltimoreCyberTrustRoot.crt.pem -p

I have followed other StackOverflow / Github questions related to this and I followed their configurations like this:

const mysql = require('mysql2');
...
var sequelize = new Sequelize(config.db, config.username, config.password, {
    host:    "<my-db>.mysql.database.azure.com",
    port:    3306,
    dialect: 'mysql',
    dialectOptions: {
        ssl: {
            ca: fs.readFileSync(__dirname + "/ssl/BaltimoreCyberTrustRoot.crt.pem")
        }
    }
});

Do I need to set additional key/cert under ssl?

ssl: {
    key: fs.readFileSync(__dirname + "./certs/client-key.pem"),
    cert: fs.readFileSync(__dirname + "./certs/client-cert.pem"),
    ca: fs.readFileSync(__dirname + "/ssl/BaltimoreCyberTrustRoot.crt.pem")
}

I am using Node 12 (Node 12.13 in Azure App Service) and here's my package.json dependencies:

"dependencies": {
    "body-parser": "^1.19.0",
    "express": "^4.17.1",
    "faker": "^4.1.0",
    "mysql2": "^2.1.0",
    "sequelize": "^5.21.5"
}

Upvotes: 2

Views: 995

Answers (1)

Jason Pan
Jason Pan

Reputation: 21873

According my test, I can connect to mysql. You can add additional key/cert yes or not.

If you add, you can see my code like below,

/*configuration*/
const sequelizeInstance  = new Sequelize("***db", "azure_root@***mysql", "Ja***.****20", {
host: "***mysql.mysql.database.azure.com",
dialect: 'mysql',
dialectOptions: {
    ssl: {
        ca: fs.readFileSync(path.resolve(__dirname, 'BaltimoreCyberTrustRoot.crt.pem'));
    }
}
});

/*test connection*/
try
{
    sequelizeInstance.authenticate();
    console.log('Connection has been established successfully.');
} 
catch (error) {
    console.error('Unable to connect to the database:', error);
}

If not, you just set ssl=true like the document .

Hope it's useful to u.

Upvotes: 2

Related Questions