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

Getting Started with MariaDB using Docker and Node.js

probablyrealrob profile image Rob Hedgpeth ・4 min read

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 

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!

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;

Then create a new table.

CREATE TABLE demo.people (name VARCHAR(50));

Finally, insert a couple records.

INSERT INTO demo.people VALUES ('rob'), ('tracy'), ('sam'), ('duke');

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

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

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

$ npm install MariaDB

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);
        });
      });
    }
  } 

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}`));

Finally, run the node application.

$ npm start

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

Which yields the following JSON response payload:

[{"name":"rob"},{"name":"tracy"},{"name":"duke"},{"name":"sam"}]

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.

Posted on by:

probablyrealrob profile

Rob Hedgpeth

@probablyrealrob

Husband • Dad • Coder • Speaker • Writer

Discussion

markdown guide