Getting Started with MariaDB using Docker and Node.js
Tags: mariadb, docker, node, sql
Published: 2020-04-13 15:06:39


It's no secret that [MariaDB](http://www.mariadb.com) 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](https://mariadb.org/) is the custodian of the MariaDB community code and guardian of the MariaDB community.
* [﻿MariaDB Corporation](https://mariadb.com/) 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](https://mariadb.com/docs/features/mariadb-columnstore/) and [HTAP](https://mariadb.com/docs/solutions/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](http://www.docker.com) and [Node.js](https://nodejs.org/), 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.

* [﻿MariaDB client﻿](https://mariadb.com/products/skysql/docs/clients/)
* [﻿Node.js](https://nodejs.org/en/download/) (and NPM - Node Package Manager)
* [Docker﻿](https://www.docker.com/products/docker-desktop)

# Using a MariaDB Docker Container

To pull the [MariaDB Server](https://mariadb.com/docs/) [image](https://hub.docker.com/r/mariadb/server) and spin up a container, simply open a terminal window and run the following.
```bash
$ 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](https://hub.docker.com/) 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.
﻿```bash
$ 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.
```sql
CREATE DATABASE demo;
```
Then create a new table.
```sql
CREATE TABLE demo.people (name VARCHAR(50));
```
Finally, insert a couple records.
```sql
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](https://www.w3schools.com/nodejs/nodejs_get_started.asp). For simplicity, I used "server.js". 

Then, within a terminal that the directory location, execute the following.
```bash
$ 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](https://expressjs.com/) package which will be used as a lightweight web framework by the Node app.
```bash
$ npm install express
```
Install the [MariaDB Node.js connector](https://mariadb.com/kb/en/nodejs-connector/), which will be used to connect to and communicate with your MariaDB instance.
```bash
$ npm install MariaDB
```
Now it's time to add code to connect to MariaDB. To do this first create a new (reusable) [module](https://nodejs.org/api/modules.html) 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.
```javascript
// 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](https://github.com/motdotla/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.
```javascript
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.
```bash
$ 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](https://curl.haxx.se/) command:
```bash
$ curl http://localhost:8080/people
```
Which yields the following JSON response payload:
```son
[{"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](https://github.com/rhedgpeth/mariadb_sample).

# 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](http://www.mariadb.com) has to offer and how you can use a truly innovative database to create modern applications.