Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to securely connect to MySQL database on another server?

I'm attempting to link my Discord bot with a MySQL database that is on another server. However, this example is apparently insecure:

const mysql = require('mysql');
const connection = mysql.createConnection({
  host     : 'hostname',
  port     : 'portnum',
  user     : 'db_user',
  password : 'db_user_password',
  database : 'db_name',
  charset  : 'utf8mb4'
});

How would I go about establishing a (more) secure connection?

like image 874
Shahmeer Naqvi Avatar asked May 30 '19 12:05

Shahmeer Naqvi


1 Answers

If its a hosted database server and you have the secured endpoint URL (meaning https:// host) then just use that as the hostname host: 'hostname' and that should be enough.

If it's a private server that you own and you have the SSL certificates then you can use the following:

const fs = require('fs');
const mysql = require('mysql');

var connection = mysql.createConnection({
    host: '127.0.0.1',
    port: '3306',
    user: 'root',
    password: 'passw0rd',
    database: 'test',
    ssl: {
        ca: fs.readFileSync(__dirname + '/certs/ca.pem'),
        key: fs.readFileSync(__dirname + '/certs/client-key.pem'),
        cert: fs.readFileSync(__dirname + '/certs/client-cert.pem')
    }
});

connection.connect();
like image 167
Sohail Avatar answered Sep 21 '22 01:09

Sohail