This article shows how to put MongoDB-ExpressJS/NodeJS-AngularJS in a single Docker container. AngularJS can be included with just a ‘script’ tag in HTML, the following steps are for MongoDB, ExpressJS, and NodeJS.

package.json

{
  "name": "mena",
  "version": "0.1.0",
  "description": "Simple MENA integration",
  "author": "Dat Dinhquoc <datdq@abivin.com>",
  "main": "server.js",
  "scripts": {
    "start": "node server.js"
  },
  "dependencies": {
    "express": "^4.13.3",
    "mongodb": "~2.0"
  }
}

server.js

"use strict";

//library modules
var Express = require("express");
var MongoDb = require("mongodb");

//constants
const PORT = 80;

//app
var app      = Express();
var dbClient = MongoDb.MongoClient;

//routes
app.get("/",function (request,response) {
  dbClient.connect("mongodb://localhost:27017/mena",
  function(error,db){
    if (error) {
      response.send("Failed to connect to MongoDB<br/>"+
      JSON.stringify(error));

      return;
    }

    response.send("Connected to MongoDB successfully!");
    db.close();
  });
});

//start app
app.listen(PORT);
console.log("MENA running on port "+PORT);
console.log("Run mongod inside container "+
"if this server.js fails to connect");

Notes:

  • After writing the code, use Docker to build image and push to Docker Hub
  • When ‘mongod‘ doesn’t start inside the container, start using Docker ‘exec’ command or shell into it to exec (Docker container uses Moby Linux, the shell is ‘sh‘ instead of ‘bash’).
$ docker exec -i SOME_CONTAINER_ID mongod
#or:
$ docker exec -i SOME_CONTAINER_ID sh
mongod
Ctrl+C

Reference:

https://nodejs.org/en/docs/guides/nodejs-docker-webapp/

Advertisements