Dockerize Development with the JavaScript MERN Stack

The MEAN Stack (MySQL, ExpressJS, ReactJS, NodeJS) has risen recently, using a single language, JavaScript, to build applications.

Setting up a development environment for the MERN Stack can be a problem if you’re not used to Linux or Mac, or you’re on Windows (installing tools on Windows is a pain). I’ll show you a way to use Docker and Docker-Compose to set up a MERN Stack environment that runs fine on Windows, Mac, or Linux, true to the lazy spirit of devs, install one and develop anywhere.

Docker

Why Dockerize?

First, imagine you and your teammate are working on the same project. One fine day your teammate runs the source code to debug, but the result differs from what you get on your machine with the same data.

There can be several causes, for example your OS and your teammate’s are different, the library versions on your machine and theirs differ, etc.

Docker was born to solve problems like these. Put simply, a Docker container can be thought of as a “computer” living inside your computer. The cool part is you can send that “computer” to your friends and teammates so they can boot it up and run the code and get exactly the same result you see on your machine.

Docker also lets project members set up a coding environment in a blink, without caring about docs and installation, with just one command.

docker-compose up

Prerequisites (Google the keywords)

  • Git
  • Docker: “Playing around” with Docker in 5 minutes
  • Docker-compose: Basically used to trigger several Dockerfiles at once, and more
  • Javascript with Node.js and React, npm, yarn
  • A few commonly used terminal/bash commands

The problem

Since we use the MERN Stack, we need 3 components, Node.js Express (api), React (webapp), and MySQL (dbms), to run the full code flow. MySQL has no source code, so I only use git to store the source code of the api and webapp. The rest, like mysql and Node.js dependencies, go in .gitignore.

The React and Node.js source code naturally belong in 2 separate repo directories, but to make it easy to trigger with docker-compose, I’ll put the 2 repos inside one big repo (called a monorepo).

Then we create the repo for each part and write the Dockerfile for it.

Node.js

Here I only code a basic express server as a sample: Express for server/routing, Sequelize as the ORM, Morgan for the logger. In general, a basic API server needs about that much.

The repo’s path/context path in this monorepo is ./server.

const express = require("express")
const app = express()
const port = 3000
const morgan = require("morgan")
const sequelize = require("./db")

app.use(morgan("combined"))

app.get("/", (_, res) => {
  res.send("Hello world!")
})

// Some other routing and handler...

sequelize
  .authenticate()
  .then(() => {
    console.log("Connection has been established successfully.")
  })
  .catch(err => {
    console.error("Unable to connect to the database:", err)
  })

app.listen(port, () => console.info(`Example server listening on port ${port}`))

Remember to split the source code into a src directory so the Dockerfile is easier to write later. Leave the rest, like node_modules and package.json, alone.

Also, to help with dev, I use nodemon for hot reload on every code change, instead of having to restart the container.

"scripts": {
    "start": "node src/index.js",
    "dev": "nodemon src/index.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },

A simple Dockerfile looks like this:

// Use the alpine image to stay light (80MB) instead of the original 800MB image
// In exchange, alpine is so light that things like git and ssh are missing, install them yourself if you need them
FROM node:10.15.3-alpine as builder

// Like yarn, for example, you have to install it yourself
RUN apk add yarn

// Create the directory for the code at /root/src/api, the path can be whatever you like
RUN mkdir -p /root/src/api
// Workdir sets the context for subsequent commands
WORKDIR /root/src/api
// When running with nodemon, PATH needs to be set
ENV PATH /root/src/api/node_modules/.bin:$PATH

// Copy from the Dockerfile's context into Docker's context
COPY . .

// Install dependencies
RUN yarn

// Open port 3000
EXPOSE 3000

// When the image runs, it runs npm run dev
// Here I set the dev script to run nodemon
ENTRYPOINT ["npm","run","dev"]

There’s also the volume mapping, which will be written in docker-compose.yml at the root context of the monorepo.

Basically, this Dockerfile can already build and run.

React

The repo’s path/context path in this monorepo is ./webapp.

React is simpler to init thanks to the create-react-app script. The index.js file is basically:

import React from "react"
import ReactDOM from "react-dom"

ReactDOM.render(<div>Siple demo, hehe.</div>, document.getElementById("root"))

Other parts like Webpack and Babel are handled by create-react-app, so to run dev we just run create-react-scripts as defined in package.json. Since port 3000 is already used by the API, React will run on port 3001:

"scripts": {
    "start": "PORT=3001 react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
},

React’s Dockerfile is similar to the API’s, since both run on Node.js:

FROM node:10.15.3-alpine as builder

RUN apk add yarn

RUN mkdir -p /root/src/app
WORKDIR /root/src/app
ENV PATH /root/src/app/node_modules/.bin:$PATH

COPY . .

RUN yarn

EXPOSE 3001

ENTRYPOINT ["npm","run","start"]

Docker-Compose

Docker-compose

I’ll handle the volume mapping and MySQL in docker-compose too. MySQL already has a ready-made image that’s good enough, so there’s no need to write a Dockerfile.

MySQL’s data is mapped outside the container so it isn’t lost when the container stops, under the ./mysql context. This should go in .gitignore so it doesn’t get pushed to Git.

version: "3"
services:
  api:
    build:
      context: ./server
    links:
      - database:database
    expose:
      - 3000
    ports:
      - 3000:3000
    image: server-dev
    container_name: server-dev
    volumes:
      - ./server/src:/root/src/api/src
    tty: true
  web:
    build:
      context: ./webapp
    expose:
      - 3001
    ports:
      - 3001:3001
    image: web-dev
    container_name: web-dev
    volumes:
      - ./webapp/src:/root/src/app/src
      - ./webapp/public:/root/src/app/public
    tty: true
  database:
    image: mysql:5.7
    container_name: db-dev
    restart: always
    environment:
      MYSQL_DATABASE: "example_dbname"
      MYSQL_USER: "username"
      MYSQL_PASSWORD: "password"
      MYSQL_ROOT_PASSWORD: "password"
    expose:
      - 3306
    ports:
      - 3306:3306
    volumes:
      - ./mysql:/var/lib/mysql

Note that in the api service definition, since the api connects to the mysql database, we need to add links so the api container can reach the mysql container. The hostname in the connect string is then database (as defined in links) instead of localhost.

For volume mapping, we only map the source code. Things like .git and node_modules don’t need mapping since they’re already in the image.

In the end we have a complete monorepo that team members can pull and bring up with docker-compose up.

Whenever you add a dependency, you can edit package.json and then rebuild the image to add that dependency to the docker image: docker-compose build.

Docker

Github repo link for a closer look: Dockerize MERN, remember to star it on github if you like it 😃

Dockerfiles for other stacks like Vue/Angular are quite similar since they’re all based on the Node.js environment.

Also remember to write .gitignore and .dockerignore to ignore directories like MySQL data, Node.js dependencies, or React’s build directory. The only thing that should be in git is the source code.

Docker family