Docker: NodeJS, MongoDB, MySQL

Kafka
2 min readOct 14, 2020

I had a project recently were they were using NodeJS, MongoDB and MySQL as their tech stack. The problem was that the developers were using different OS’s for development which brought a non standard developer environment. So the solution was everyone use Docker.

SOURCE CODE:

git clone https://github.com/ottokafka/docker_nodejs_mongodb.git
git checkout mySQL_Mongodb_NodeJS

We need to create a docker-compose.yml

docker-compose.yml

NodeJS Server

Below we dont use localhost to connect to our databases we use the names we gave in the docker-compose file

const express = require('express');
const app = express();
const mongoose = require('mongoose');
const mysql = require('mysql');
const PORT = 4000;// USE THIS BECAUSE of based of name we gave the database
mongoose.connect('mongodb://database_mongodb:27017/mydb').then(() => console.log("connected to mongodb")).catch((err) => console.log(err))
// Connect to mySQL database
mysql.createConnection({
host: "database_mysql",
user: "root",
password: "root"
}).connect(() => console.log("MySQL connected"))
// Gives user a response when visiting localhost:4000
app.get('/', function (req, res) {
res.json({ "Whats up": "world" });
});
// Starts up server and displays the port the server is running on
app.listen(PORT, function () {
console.log('Your node js server is running on PORT:', PORT);
})

Run docker-compose.yml

docker-compose up --build

All done you should see something like this

Docker GUI

In the container tab we will see our 3 new created containers

Lets connect to our Docker NodeJS app in a browser in localhost:4000

Test: nodemon hot-reload

Were adding some text in the res.json({ “Whats up”: “World were using docker with nodemon”})

Save the file and you should see in the terminal: nodemon restarting due to changes. In the browser localhost:4000 you should see the change to the text.

Well there you have it, a cleaner more standard workflow using Docker, NodeJS, MongoDB and MySQL.

That’s it guys. I hope you guys got something out of this article. If this article helped you go ahead and smash that clap button. Cheers 🍺

--

--

Kafka

“Genius” is 1% inspiration and 99% perspiration. Accordingly, a ‘genius’ is often merely a talented person who has done all of his homework — T.E.