Get Rewarded! We will reward you with up to €50 credit on your account for every tutorial that you write and we publish!

Connect to Dockerized MariaDB with Node.js via Unix socket

profile picture
Author
Reza Gharabaghi
Published
2024-10-09
Time to read
4 minutes reading time

Introduction

One of the easiest ways to connect and send SQL queries to MariaDB is the popular JavaScript runtime called Node.js.

We need the MySQL library to interact with MariaDB and send a simple SELECT query.

As I said in the first tutorial, the common way for connecting to a database is via a TCP connection (127.0.0.1:3306). Opening an extra port equals less security. Hackers try to connect to a database via open ports like 3306. Unix sockets are only available for processes inside our Linux machine.

Another advantage of Unix socket over TCP connection is the speed.

For more informations, it's better to take a look at this and this link.

This tutorial is split into multiple parts.

Series index

  1. Dockerizing MariaDB with Alpine Linux
  2. Import and Export data in Dockerized MariaDB
  3. Connect to Dockerized MariaDB with Node.js via Unix socket (You are here)

Prerequisites

  • Server with Rocky Linux 9

Step 1 - Node.js structure

For this tutorial I don't want to Dockerize the Node.js app, so I install Node.js with the dnf command in Rocky Linux. So simple:

dnf -y install nodejs

And now you can check the version of Node.js with the node -v command.

Every Node.js project contains atleast one package.json file and a JavaScript entry point file, which I named index.js.

Put these two files in a new directory, for example:

mkdir /nodejs-socket
cd /nodejs-socket

package.json

{
    "name": "send_query",
    "type": "module",
    "version": "1.0.0",
    "main": "index.js",
    "dependencies": {
        "mysql2": "^3.11.1"
    }
}

index.js

import mysql from 'mysql2/promise';

async function db_connection() {
    const new_connection = await mysql.createConnection({
        user: 'root',
        // This is the MariaDB Unix socket file
        socketPath: '/maria/socket/maria.sock',
        database: 'mysql'
    });

    return new_connection;
}

async function main() {
    const new_connection = await db_connection();
    const db_result = await new_connection.query('SELECT * FROM user;');
    new_connection.end();

    console.log(db_result[0][0].User);
    // mariadb.sys
}

main();

Now, you have to install Node.js dependencies with the npm install command.

After installing dependencies, you will see the node_modules directory and the package-lock.json file in your Nodes.js directory.

Step 2 - Running Node.js

It's time to run your code with the node index.js command. The console.log() statement will print the first user (mariadb.sys) of the query in terminal.


Now, we want to send a query and get all players from the players table in the tennis database. We created the tennis database in the previous tutorial. Now, you have to update the index.js file and modify 3 lines:

  • Modify database: 'mysql' to database: 'tennis'
  • Modify SELECT * FROM user; to SELECT * FROM players;
  • Modify console.log(db_result[0][0].User); to console.log(db_result[0]);

Now run this command again:

node index.js

You will see an array like this:

[
    {
        id: 1,
        name: 'Novak Djokovic',
        gender: 'Male'
    },
    {
        id: 2,
        name: 'Maria Sharapova',
        gender: 'Female'
    },
    {
        id: 3,
        name: 'Roger Federer',
        gender: 'Male'
    }
]

Good job, this is the end point of the Dockerizing MariaDB with Alpine Linux tutorial series.

Conclusion

In this tutorial we send our SQL queries via Unix socket to Dockerized MariaDB. This series is a good point for you to work with Docker more and more. Isolating every app via Docker is very good, because Docker containers encapsulate apps and their dependencies, and ensure that they run consistently across different environments.

For example, you can run your Dockerized MariaDB on any machine that has Docker already installed on it.

License: MIT
Want to contribute?

Get Rewarded: Get up to €50 in credit! Be a part of the community and contribute. Do it for the money. Do it for the bragging rights. And do it to teach others!

Report Issue

Discover our

Dedicated Servers

Configure your dream server. Top performance with an excellent connection at an unbeatable price!

Want to contribute?

Get Rewarded: Get up to €50 credit on your account for every tutorial you write and we publish!

Find out more