Building Your First Dockerized MERN Stack Web App

Aravind Kumar Vemula
6 min readJun 18, 2022

Hi, everyone. Let’s build your dockerized mern stack web app.

You will find all the source code in the GitHub repository. Which is free and open to contribute for everyone.

https://github.com/lmas3009/Dockerized-MERN-Stack

Let’s start creating a backend part

For the backend part, we will be using Express, MongoDB, and NodeJs.

Now let's start creating a node server.

Enter this command in the command prompt npm init -y which is used to initialize your project.

For this project we will be installing 4 packages:

  1. Express, 2. Mongoose, 3. Cors, 4. Body-Parser
npm i express mongoose cors body-parser

Now create index.js file and import all the packages.

import Express from "express"import cors from "cors"import bodyParser  from "body-parser"import mongoose from "mongoose"

Now create a simple express server that displays Welcome to docker tutor

const app = Express()app.use(cors())app.use(bodyParser.json());app.get("/",(req,res)=>{   res.send("Welcome to docker tutor")})app.listen(3001,()=>{ console.log("app is listening on port: 3001")})

After running the project using node index.js in the terminal, you will see like

Now connect the node server to MongoDB.

const database = "mongodb://localhost:27017/docker-mern_stack";mongoose.connect(database,{useNewUrlParser: true,useUnifiedTopology: true}).then(()=>{console.log("connected to DB")}).catch((err)=>{console.log("Not connected to DB")})

This is to connect your MongoDB compass to the node server using the database URL. The default URI of MongoDB is mongodb://localhost:27017 and the additional is the database name /database_name

Now if you run the server again you will in the terminal as connected to DB or if you see Not connected to DB console the err value and modify based on the error.

Now let’s create a model and name it userinfo.js. Here you will be adding the requirements that the database table should have.

Now create a folder called models in the server directory and create a file called userinfo.js

import mongodb  from "mongoose";const userinfo = new mongodb.Schema({ username:{  type: String,  required: true // username should be required }, email:{  type: String,  required: true // email should be required }, phone:{  type: String,  required: true // phone number should be required }})export default userinfo;

Here we are creating a userinfo table with the column names and with the conditions.

Now under index.js file, we will be creating a route to get and post the data.

app.post("/datapost",(req,res)=>{ mongoose.model("Datapost",userinfo).create(req.body,(err,data)=>{ if(err){  res.send({   result: []  }) } else{  res.send({   result: data  }) } })})

This is the post route. Here we are getting the data from the user and inserting the data in MongoDB.

app.get("/dataget",(req,res)=>{ mongoose.model("Datapost",userinfo).find({},(err,data)=>{ if(err){  res.send({  result: []  }) } else{ res.send({  result: data  }) } })})

This is the get route. Here we will be sending the data to the user from our Database.

You just built a backend server using Nodejs, Express, and MongoDB.

Now we need to containerize the server using docker. For that, we need to create a file called Dockerfile and .dockerignore files.

Dockerfile is the main file where it contains all the commands a user could call on the command line to assemble an image.

.dockerignore is the file that is similar to the .gitignore file which allows you to specify a list of files or directories that Docker is to ignore during the build process.

Under Dockerfile we will be adding:

FROM node:alpineWORKDIR /node/nodeappCOPY . .RUN npm installCMD ["npm","start"]

Here we are installing a docker file called node:alpine which is a Linux distribution system.

WORKDIR is to set the working directory for the server

COPY is to copy the files from the server to the working directory

RUN is to install any packages

CMD is to run the command in the terminal.

Under .dockerignore file

node_modules

And that’s it you just created a backend server and containerize with the docker

Let’s start creating a frontend part.

I am using react for the frontend part.

Create a new react project 👇
npx create-react-app userinfo

Install Axios packages to make routes to the server
npm i axios

Follow this documentation on integrating tailwindcss in react project.

Now under App.js, Create a simple table using tailwindcss. which as Username, Email Id, and Phone Number. Which looks like this:

Now create a simple form where it accepts username, email id, and phone number as an input.

Now create a handlesubmit function where it post the data to server.

const handleSubmit = (e) =>{ e.preventDefault(); instance.post("/datapost",{ username:username, email:email, phone:phone }).then((res)=>{ alert("Submited") })}

And a useEffect function which is use to update the result list every time when the new data inserted.

useEffect(()=>{ instance.get("/dataget").then((res)=>{  setResult(res.data.result) })})

Now display the result in the table

{result.map((item, index) => ( <tr>
....
</tr>
))}

You just built a frontend part and Now we need to containerize the react app.

Follow the same process done with server part. creating Dockerfile and .dockerignore file.

And that’s it you just created a frontend part and containerize with the docker.

Let’s start creating the Docker compose file

Docker-Compose is a tool for defining and running multi-container Docker applications.

Now we are composing the two docker containers.

In the Main directory create a file called docker-compose.yml all the compose files are in yml format.

Under docker-compose.yml file we are adding

version: "3.9"services: react:  build: ./userinfo/  ports:    - "3000:3000" node:  build: ./server/  ports:    - "3001:3001" mymongo:  image: mongo

For every compose file version is required.

Let’s start with services. Here react: is the name we given to the react app docker, under build is to run the Dockerfile under your project, with the ports 3000:3000. Same for the node: .

Now mymongo: is the name we given to the image called mongo. For this project need to MongoDB to interact with the user information.

Now if the server need to connect to database we need to change the localhost to the mymongo in the database url. Because while running the docker application mongo will be running on the name which we have given.

Done you just created a docker-compose file.

Now we need to run the docker compose file

docker-compose up -d

This is to run the application and stay running continuously in background.

Now open a any browser and enter localhost:3000 you will be seeing the react app running and which is connected to backend part and Database.

Photo by Priscilla Du Preez on Unsplash

Thank’s for reading the article till the end…💗

If you like the article support me with buymecoffee🍵.

--

--