Docker has become a standard tool among DevOps and Infrastructure people and for the daily work of any developer. This article is aimed at Docker beginners who want to get a fully working instance of a Node Express and MongoDB app up and running in a matter of seconds for daily work.
Setup Node Express and MongoDB in Docker
Docker will help you spin up containers (which behave like Virtual Machines but are not that heavy) and run your app on them. In addition, it gives us the ability to port the container anywhere we want on any server we want; moving from local to production gets secure and less buggy as the environment of the container running the app does not change.
We will start this tutorial by creating a simple Node Express application. So let us do it.
Step 1: Install the dependencies.
Create a project folder in your leading directory by the following command.
mkdir newdock
Go into the folder.
cd newdock
Install the following dependencies.
yarn add express mongodb or npm install express mongodb --save
I am using the Yarn package manager, and you can also use npm.
Step 2: Create a server.js file.
First, we need to create one database file that returns the database string. So create one file db.js inside the root.
// db.js module.exports = { DB: 'mongodb://mongo:27017/newdock' }
Notice that I have not written the localhost in the connection string. That is because we are connecting our Express application to the mongodb container. You will see this later in this article.
Write the following primary express application inside a server.js file.
// server.js const express = require('express'); const app = express(); const mongodb = require('mongodb'); const config = require('./db'); const PORT = 4000; const client = mongodb.MongoClient; client.connect(config.DB, function(err, db) { if(err) { console.log('database is not connected') } else { console.log('connected!!') } }); app.get('/', function(req, res) { res.json({"hello": "world"}); }); app.listen(PORT, function(){ console.log('Your node js server is running on PORT:',PORT); });
I have created an express instance and connected our application to the database.
Our Node application serves at Port: 4000, and when we hit the root URL(‘/’), then in response, we get the JSON data.
We have installed a mongodb package that can help us to connect our app to the mongodb database.
Now, our application is ready. The next step is to write the Dockerfile and docker-compose.yml file.
Step 3: Write Dockerfile inside the root folder.
Inside the root folder, create a file called Dockerfile.
FROM node:7 WORKDIR /app COPY package.json /app RUN npm install COPY . /app CMD node server.js EXPOSE 4000
What it does is, we will create one container called an app, and in that container, our whole project dependencies have resided. So when we deploy our container to the server, it will first install all the dependencies and then spin up the node server. The application will run on port 4000.
Step 4: Write the docker-compose.yml file.
Inside the root folder, create one file called docker-compose.yml file. Copy the following code.
version: "2" services: app: container_name: app restart: always build: . ports: - "4000:4000" links: - mongo mongo: container_name: mongo image: mongo ports: - "27017:27017"
Here, we are building two containers.
- app container(It is our express app)
- mongodb container(mongodb server).
Step 5: Build the Docker containers.
If you have not installed Docker, please install it using this link.
Now, open the terminal at the project’s root and type the following command.
docker-compose build
It will create the containers and put our whole code inside them. Then, it will generate step by step. Finally, install all the dependencies and last successfully form the containers. Now our containers are built successfully; we need to run the container.
Step 6: Run the containers.
We can up our containers using the following command.
docker-compose up
If everything is fine, you can see something like this.
Our app is running on port 4000, and we have successfully connected to the mongodb database.
Now, remember, when you need to change the file, you need to rebuild the container and run. Otherwise, your latest changes will not reflect on the container.
Go to the browser and hit this URL: http://localhost:4000/.
You can see that we are getting the JSON response. We have also connected our express application to the mongodb database.
That’s it for this tutorial. Thanks for taking it.
hi Krunal,
thanks for this tutorial!
BUT
i cant get it to work….
i even cloned it. it says in my docker-terminal that its on port 4000. but…its not there on the browser.
http://localhost:4000/
gives me nothing.
could there be a change somewhere? an update? im not getting any errors also. everything looks just fine. all, but the response in the browser.
Regards, F
Hi Krunal,
I always receive the message “database is not connected”, looging the err in the callback this is the message
“MongoNetworkError: failed to connect to server [mongo:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 172.18.0.2:27017]”
But if i try to connect to the mongo instance with another software it is up and running.
Any Idea what I can try?
Thanks for the tutorial
Have you solved the problem? If yes, please tell me how to solve it.
In node application, Change mongodb path to “mongodb://mongo:27017/database_name” and also make sure your mongodb container name should be “mongo”
In my node application, i have the path as “mongodb://mongo:27017/database_name” and also the the container name is mongo. But still i couldn’t connect to mongo in docker. Any idea why?
HELP THE SAME PROBLEM
– remove containers
– make sure the mongo uri uses the container name found in the compose file
– lock down a specific mongo version for example 3.6.13
do a docker-compose build to create the containers first, then docker-compose up
Before I was using docker-compose up –build which should rebuild each time but if your mongo container if not running in the first place because of some error you can see how this won’t work
Have you solved the problem? If yes, please tell me how to solve it.
Have you solved the problem? If yes, please tell me how to solve it.
Good Article, it’s always best to have separate containers for application and database and have them run using docker-compose.
– remove containers
– make sure the mongo uri uses the container name found in the compose file
– lock down a specific mongo version for example 3.6.13
do a docker-compose build to create the containers first, then docker-compose up
Before I was using docker-compose up –build which should rebuild each time but if your mongo container if not running in the first place because of some error you can see how this won’t work
add this ander “app:”
‘depends_on:
– mongo’
hope that’s help!
If you have a mongo connection error try this:https://dev.to/hugodias/wait-for-mongodb-to-start-on-docker-3h8b
Thank you for the tutorial. I am new to Docker, Mongo. I receive the following error when I type ‘docker-compose build’ in the terminal:
ERROR: Service ‘app’ failed to build : COPY failed: stat /var/lib/docker/tmp/docker-builder539072260/package.json: no such file or directory
In the tutorial, there is no mention of the creation of a package.json file, thus how could we ‘copy’ it. I understand the package.json file should include descriptions as well as dependencies…can someone clarify:
1) should I create the package.json file in the project root directory
2) what should the contents of the package.json file include?
Thank you.