Last Updated: June 19, 2019

How to create docker image with NodeJs and Grunt?

Description: In this post I'm gonna show you how to create Docker Image for Nodejs project using Grunt

Note:
Grunt:  Its a Javascript task runner. In this project we'll use for minification of our .js file.
Docker:  Its a platform where we gonna place containerised image of our NodeJs Project.

Github Project

So lets get started.

Step 1:  Create index.js

//Import Express
var express = require('express')
var app = express()

//Import Path
var path = require('path')

//Mounting our .js from build folder.
app.use("/build", express.static(__dirname + "/build"))

//Capture the base url
app.get('/', function(req, res){
 res.sendFile(__dirname + "/index.html")
})

//Listen on port 9000
app.listen(9000, function(){
 console.log('Lisening on port 9000')
})

Note: build folder will be created after we run our Gruntfile

Step 2:  Create package.json

{
  "name": "demo-docker-nodejs-grunt",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "grunt uglify",
    "start": "node index.js"
  },
  "author": "coderconsole",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1",
    "grunt": "^1.0.4",
    "grunt-cli": "^1.3.2",
    "grunt-contrib-uglify": "^4.0.1"
  }
}


Note: 
dependencies: Its contains all the dependencies we needed within the project.
scripts: Its contains grunt uglify to minify our .js and and start to start the nodejs app.

Step 3:  Create Gruntfile.js parallel to package.json and echo.js within src/ folder(just to separate our code structure)

Gruntfile.js
//Setting grunt
module.exports = function(grunt){

    //Setting Init Config from package.json
    grunt.initConfig({

        //Read package.json and assign it to 'pkg'
        pkg: grunt.file.readJSON('package.json'),


        uglify: {
              options: {
                banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'
              },
              build: {
                src: 'src/echo.js',
                dest: 'build/echo.min.js'
           }
        }
    });

    // Load "uglify" task
    grunt.loadNpmTasks('grunt-contrib-uglify')

    // Load default task
    grunt.registerTask('default', ['uglify'])

};


echo.js within src/ folder
function echoNameFunction(data) {
       return "<h2>Welcome " + data + "</h2>"
}



Step 4:  Create Dockerfile
# Select the Node Module
FROM node:11

# Add the working Directory
WORKDIR /app

# COPY out package.json to our working directory /app
COPY package*.json /app/

# RUN npm install which will download all the dependencies from package.json
RUN npm install

# COPY the current content to /app folder structure
COPY . /app/

# UGLIFY the src/*.js
RUN npm run build

# EXPOSE our port
EXPOSE 9000

# Create EntryPoint of index.js file
ENTRYPOINT ["node", "index.js"]


Note: Dockerfile contains steps which get executed sequentially. Please read comments for what each steps does.

Step 5:  Create index.html
<html lang="en">
<head>
    <script src="build/echo.min.js"></script>

    <script>
        function display(){
            var name = document.getElementById('firstname').value
            document.getElementById('display').innerHTML = echoNameFunction(name)
        }
    </script>
</head>
<body>
<label for="firstname">Enter your first name</label>
<input id="firstname" name="firstname" type="text"/>
<button onclick="display()">
    Click!
<p id="display"></p>
</body>
</html>


Step 6:  Create .dockerignore file to avoid node_modules or build folder get added into the image

**/node_modules
build/*.js
.idea/

Step 7:  Finally, lets create our docker image and run it using below command.
Build Docker image
docker build -t docker-node-grunt:1.0.0 -f Dockerfile .

Run Docker image
docker run -p 9000:9000 docker-node-grunt:1.0.0

Now, open browser and hit url http://localhost:9000/












Bingo! We've successfully deployed our nodeJs application in docker using grunt.

Github Project

#codingIsAnArt 

3 comments :

  1. The images should be captivating if at all possible. A website that simply posts useless and meaningless images is just as bad as a website that does not use images.Photo Retouching Service

    ReplyDelete

  2. Awesome expected post you shared here, I will require it many times, and here the outstanding selection of topic also makes me more jolly, please hope more blog post we get from you. Thanks advances!!!


    Here the information you included is very important to match the area of focus, besides we will be very happy if you regular set up like this post. Thanks in advance!!

    ReplyDelete

Your comments are valuable for us !!!