How to setup a Docker NodeJS MongoDB developer environment.

I needed a fast workflow for me and my team so I looked up how to setup a fast workflow with Docker to have a standard dev environment.
We need create a docker-compose.yml
Nodemon: if you worked with NodeJS before you already know nodemon and its the most important package to make this workflow function in Docker.
SOURCE CODE: git clone && git checkout
git clone https://github.com/ottokafka/docker_nodejs_mongodb.git
git checkout nodejs_mongodb
Now we need to create our docker-compose.yml
docker-compose.yml
NodeJS server
Connecting to the mongoDB is a little different here. We won’t be using “localhost” we will be using “database” which is the name of the mongoDB service we set in docker-compose.yml. This will allow us to connect to our docker mongoDB container.
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const PORT = 4000;// USE THIS BECAUSE of based of name we gave the database
mongoose.connect('mongodb://database:27017/mydb').then(() => console.log("connected to mongoDB")).catch((err) => console.log(err))// 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 nodeJS server is running on PORT:', PORT);
})
Project directory structure

.dockerignore: the .dockerignore is needed to avoid node_modules being taken from the host machine to the docker container.

Run docker-compose.yml
docker-compose up --build
If things go right we should see our mongoDB up and running
Containers / Apps
So we have our 2 containers: NodeJS server & MongoDB
Lets connect to our Docker NodeJS app in a browser in localhost:4000

Should get this result: just a simple json response “Whats up world”
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 and MongoDB.
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 🍺