Connect Node.js to MySQL on Hostinger VPS

1. Install MySQL on Hostinger VPS

sudo apt update && sudo apt install mysql-server -y

Test: Check if MySQL is running:

sudo systemctl status mysql

2. Secure MySQL Installation

sudo mysql_secure_installation

Test: Log into MySQL:

mysql -u root -p

3. Create a Database & User

mysql -u root -p
CREATE DATABASE mydb;
CREATE USER 'myuser'@'%' IDENTIFIED BY 'mypassword';
GRANT ALL PRIVILEGES ON mydb.* TO 'myuser'@'%';
FLUSH PRIVILEGES;
        

Test: Log in with the new user:

mysql -u myuser -p

4. Allow Remote MySQL Connections (If Needed)

sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf
        

Change bind-address = 127.0.0.1 to bind-address = 0.0.0.0

sudo systemctl restart mysql
sudo ufw allow 3306/tcp
sudo ufw reload
        

5. Install Node.js and MySQL Driver

sudo apt install nodejs npm -y
mkdir mynodeapp && cd mynodeapp
npm init -y
npm install mysql2
        

Test:

node -v
npm -v

6. Connect Node.js to MySQL

const mysql = require('mysql2');
const connection = mysql.createConnection({
    host: 'localhost',
    user: 'myuser',
    password: 'mypassword',
    database: 'mydb'
});
connection.connect(err => {
    if (err) {
        console.error('Database connection failed:', err.stack);
        return;
    }
    console.log('Connected to MySQL as ID', connection.threadId);
});
connection.end();
        

Run:

node index.js

7. Deploy & Keep Node.js Running

npm install -g pm2
pm2 start index.js
pm2 save
pm2 startup
        

Final Checklist: