DEV Community

Cover image for Getting Started with MariaDB using Docker and Node.js
Rob Hedgpeth
Rob Hedgpeth

Posted on

Getting Started with MariaDB using Docker and Node.js

It's no secret that MariaDB has become a popular database solution for developers over the past decade. Why? Well, one could argue that it's largely because it's open source and relational. So, for developers, that basically means it's free, and we get the gist of it. But that really only begins to scratch the surface.

What you may not know is that there are two groups actively contributing to MariaDB; Foundation and Corporation.

  • MariaDB Foundation is the custodian of the MariaDB community code and guardian of the MariaDB community.
  • MariaDB Corporation contributes to the community codebase, but also provides superior quality, enterprise grade products that thrusts MariaDB into the forefront of database vendors. MariaDB Corporation even offers columnar and HTAP based solutions, but I digress.

With that in mind, I've written this short walkthrough to provide a launchpad for you to get started using MariaDB with Docker and Node.js, within a matter of minutes, so you can check things out for yourself.

Requirements

Before jumping into code, you're going to need to make sure you have a few things on your machine.

Using a MariaDB Docker Container

To pull the MariaDB Server image and spin up a container, simply open a terminal window and run the following.

$ docker run -p 3306:3306 -d --name mariadb -eMARIADB_ROOT_PASSWORD=Password123! mariadb/server:10.4 
Enter fullscreen mode Exit fullscreen mode

The previous command will pull down the MariaDB Server image (if you don't already have it) from Docker Hub and create a container that you can connect to and communicate with using the MariaDB client.

Note: While you can certainly use a variety of other SQL clients, for the sake of keeping things simple and uniform, I've only included samples using the official MariaDB client.

Connect to your MariaDB instance by executing the following command in a terminal window.


$ mariadb --host 127.0.0.1 -P 3306 --user root -pPassword123!
Enter fullscreen mode Exit fullscreen mode

You should see something like the following, which means you've successfully connected to the MariaDB instance!

Next, create a new database.

CREATE DATABASE demo;
Enter fullscreen mode Exit fullscreen mode

Then create a new table.

CREATE TABLE demo.people (name VARCHAR(50));
Enter fullscreen mode Exit fullscreen mode

Finally, insert a couple records.

INSERT INTO demo.people VALUES ('rob'), ('tracy'), ('sam'), ('duke');
Enter fullscreen mode Exit fullscreen mode

Connecting to MariaDB with Node.js

Now that you've downloaded, installed, and stood up a MariaDB database, you're ready to put it to use within a new Node.js app.

To start, pick a new directory, and create a new Javascript file to be used as the main entry point for the Node server. For simplicity, I used "server.js".

Then, within a terminal that the directory location, execute the following.

$ npm init
Enter fullscreen mode Exit fullscreen mode

Feel free to fill out all of the prompts, or you can just hit the enter key through all of the options. Either way, you'll end up with a package.json file being generated next to server.js.

Note: You now have a runnable Node app, albeit a pretty uninteresting one. So, let's continue to spice it up!

Install the Express package which will be used as a lightweight web framework by the Node app.

$ npm install express
Enter fullscreen mode Exit fullscreen mode

Install the MariaDB Node.js connector, which will be used to connect to and communicate with your MariaDB instance.

$ npm install MariaDB
Enter fullscreen mode Exit fullscreen mode

Now it's time to add code to connect to MariaDB. To do this first create a new (reusable) module file called db.js.

The db module will use the MariaDB Node.js connector that will enable your app to connect to and communicate with MariaDB.

Then you'll paste the following code into it and save.

// import mariadb
var mariadb = require('mariadb');

// create a new connection pool
const pool = mariadb.createPool({
  host: "127.0.0.1", 
  user: "root", 
  password: "Password123!",
  database: "demo"
});

// expose the ability to create new connections
module.exports={
    getConnection: function(){
      return new Promise(function(resolve,reject){
        pool.getConnection().then(function(connection){
          resolve(connection);
        }).catch(function(error){
          reject(error);
        });
      });
    }
  } 
Enter fullscreen mode Exit fullscreen mode

Tip: You probably won't want to just slap all the sensitive connection information directly into your connection module. This has been done for demo purposes only. Instead, you may consider using something like dotenv to handle environmental data.

The final development step is to create an Express endpoint that uses the MariaDB Node.js connector (via db.js).

Open server.js, paste the following code into it, and save.

const express = require('express')
const pool = require('./db')
const app = express()
const port = 8080

// expose an endpoint "people"
app.get('/people', async (req, res) => {
    let conn;
    try {
        // establish a connection to MariaDB
        conn = await pool.getConnection();

        // create a new query
        var query = "select * from people";

        // execute the query and set the result to a new variable
        var rows = await conn.query(query);

        // return the results
        res.send(rows);
    } catch (err) {
        throw err;
    } finally {
        if (conn) return conn.release();
    }
});

app.listen(port, () => console.log(`Listening on port ${port}`));
Enter fullscreen mode Exit fullscreen mode

Finally, run the node application.

$ npm start
Enter fullscreen mode Exit fullscreen mode

Testing it out

Once the Node project has been started, you can test it out by executing a request. This can be done through a variety of techniques. For instance, consider executing the following curl command:

$ curl http://localhost:8080/people
Enter fullscreen mode Exit fullscreen mode

Which yields the following JSON response payload:

[{"name":"rob"},{"name":"tracy"},{"name":"duke"},{"name":"sam"}]
Enter fullscreen mode Exit fullscreen mode

Also, if you'd like to review the Node.js project in its entirety, I've pushed the complete code to this repository.

Just the beginning

Hopefully this short walkthrough has helped you get started using MariaDB with Node.js. And, yea, this was a very simple example, but it only gets more exciting from here!

I highly recommend that you check out all of what MariaDB has to offer and how you can use a truly innovative database to create modern applications.

Top comments (2)

Collapse
 
willyvaessen profile image
Willy Vaessen

While looking for a guide to using MariaDB with Node.js I came across this guide, which I followed and it works nicely. Thank you for that.

After building this I tried to use dotenv to get rid of the sensitive information in my code, but that seems to fail and I can't seem to figure out why. That's why I'm hoping you great people can help me out.

In my db.js file I have the following:

//  Create a new connection pool
const pool = mariadb.createPool({
    host: "database_server_ip",
    user: "demo_user",
    password: "MyPassword",
    database: "demo"
});
Enter fullscreen mode Exit fullscreen mode

and with this information the page localhost:8080/people gives me the result with 4 names in it, just as expected.

However, with my .env file being the following:

# .env
HELLO="World!",
DB_HOST="database_server_ip",
DB_USER=demo_user,
DB_PASSWD="MyPassword",
DB_NAME="demo"
Enter fullscreen mode Exit fullscreen mode

As soon as I replace one of the values in db.js with (for example) "process.env.DB_PASSWD" the resulting page times out, with the following in my terminal:

  return new SqlError(msg, sql, fatal, info, sqlState, errno, additionalStack, addHeader);
         ^

SqlError: (conn=-1, no: 45028, SQLState: HY000) retrieve connection from pool timeout after 10003ms
    (pool connections: active=0 idle=0 limit=10)
    connection error: Error during pool initialization: (conn=233, no: 1045, SQLState: 28000) Access denied for user 'demo_user'@'172.17.0.1' (using password: YES)
    at module.exports.createError (W:\Software_Development\Webstorm_Projects\100DaysofCode\20230827_Day27\node_modules\mariadb\lib\misc\errors.js:61:10)
    at Pool._requestTimeoutHandler (W:\Software_Development\Webstorm_Projects\100DaysofCode\20230827_Day27\node_modules\mariadb\lib\pool.js:344:26)
    at listOnTimeout (node:internal/timers:569:17)
    at process.processTimers (node:internal/timers:512:7) {
  sqlMessage: 'retrieve connection from pool timeout after 10003ms\n' +
    '    (pool connections: active=0 idle=0 limit=10)',
  sql: null,
  fatal: false,
  errno: 45028,
  sqlState: 'HY000',
  code: 'ER_GET_CONNECTION_TIMEOUT'
}

Node.js v18.17.1
[nodemon] app crashed - waiting for file changes before starting...

Enter fullscreen mode Exit fullscreen mode

What am I missing or doing wrong?
The use of the .env file itself, seems to work, since the following code:

app.get('/', (req,res) => {
res.statusCode = 200
res.setHeader('Content-Type', 'text/plain')
res.end(
Hello ${process.env.HELLO})
});

results in a 'Hello "World", on the "/" endpoint:

Collapse
 
chirunnuj profile image
George Hir

To let you know that I found this guy's tutorial on Node and mariadb is quite similar to yours but yours are written in 2020 and his is in 2021.

section.io/engineering-education/g...