Access MySQL server in private ec2 instance in nodejs

空扰寡人 提交于 2021-02-11 14:02:33

问题


I am new to AWS and Node js. I want to query a MySQL server in a private ec2 instance in a testing project which I am building using Node js. How should I go about it? Thanks

EDIT: I want to access it through my local computer. The way I came up with was:

  1. Start a terminal from node js - don't know which method would be best

  2. Use the terminal to login into public ec2

  3. connect to private ec2 through public instance

  4. launch the MySQL client through private instance and query it.

I wanted to know if there is a better way to do this. And any advice on how to achieve the same


回答1:


  1. install the package: jm-ez-mysql

    npm install jm-ez-mysql --save

    use this document url: https://www.npmjs.com/package/jm-ez-mysql

  2. configuration and connection databse database.js file

    const My = require('jm-ez-mysql');

    // Init DB Connection
    const connection = My.init({
      host: process.env.DBHOST,
      user: process.env.DBUSER,
      password: process.env.DBPASSWORD,
      database: process.env.DATABASE,
      dateStrings: true,
      charset: 'utf8mb4',
      timezone: 'utc',
      multipleStatements: true,
      connectTimeout: 100 * 60 * 1000,
      acquireTimeout: 100 * 60 * 1000,
      timeout: 100 * 60 * 1000,
    });
    
    module.exports = {
      connection,
    };
    

In express js project to configuration database

/config
  /database.js
/server.js
/.env

const http = require('http');
const app = require('express')();
require('./config/database.js');
const bodyParser = require('body-parser');
const server = http.createServer(app);

server.listen(process.env.ServerPort, '0.0.0.0', () => {
  logger.info(`Express server listening on port ${process.env.ServerPort}`);
});
  1. server.js file

    const My = require('jm-ez-mysql');

    My.first("psu_project", ["id"], "1=1 ").then(function (r) { console.log(r); });




回答2:


  1. Install the package: mysql

    npm install -save mysql

  2. Connect MySQL to the server.

Example:

const mysqlConnection = require('mysql').createConnection;

mysqlConnection = mysqlConnection({
        host: HOST,
        user: DB_USER,
        password: DB_PASSWORD,
        database: DB_NAME,
      });
mysqlConnection.connect();

mysqlConnection.query('SELECT * FROM table_name');

NOTE: query() is an asynchronous function.



来源:https://stackoverflow.com/questions/60504692/access-mysql-server-in-private-ec2-instance-in-nodejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!