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 

21 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
  3. Enroll in the leading Autocad institute in Delhi and Noida.High Technologies Solutions believes in quality training and provide innovative friendly environment.We also provide live projects, Assignments, free demo class and placement assistance. Call at 9311002620.
    autocad training institute in Delhi
    autocad training institute in Noida

    ReplyDelete
  4. You make so many great points here that I read your article a couple of times. Your views are in accordance with my own for the most part. This is great content for your readers. image typing data entry

    ReplyDelete
  5. You make so many great points here that I read your article a couple of times. Your views are in accordance with my own for the most part. This is great content for your readers. image typing data entry

    ReplyDelete
  6. Wonderful article, thanks for putting this together! This is obviously one great post. Thanks for the valuable information and insights you have so provided here. data entry images

    ReplyDelete
  7. Great Article
    Image Processing Projects




    Deep Learning Projects for Final Year




    JavaScript Training in Chennai



    JavaScript

    Training in Chennai




    The Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals,

    Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer.

    Angular Training

    ReplyDelete
  8. This comment has been removed by the author.

    ReplyDelete
  9. We offer wall Painting Servicing Dubai, house painter, villa painting Dubai, home painting Dubai, decoration wall professional painting services in Dubai, wall painting for office, apartment painting resource, We provide villa painting in Abu Dhabi but apartment painting Dubai

    ReplyDelete
  10. You really know your stuff... Keep up the good work! web hosting in pakistan

    ReplyDelete
  11. I think this is a really good article. You make this information interesting and engaging. You give readers a lot to think about and I appreciate that kind of writing.
    nodejs software developers

    ReplyDelete
  12. Thanks for letting us know about it, these information are really awesome. You can also check out https://fasterapk.com/clash-of-clans-unlimited-gems-mod-apk/ it will provide you complete apk file.

    ReplyDelete
  13. I wanted to thank you for this excellent read!! I definitely loved every little bit of it. I have you bookmarked your site to check out the new stuff you post. Thank you for taking the time to publish this information very useful

    ReplyDelete
  14. Latest growth in clipping path services is related to jewellery design. The clipping path services permit the designer huge options to assemble the jewellery. Clipping Path India

    ReplyDelete
  15. Guarantee the picture outline you purchase is no lower than 640x480 in goal. Commonly, a 7 inch edge ought to have goal of 720x480, a 8 inch ought to have 800x600 goal, and casings north of 10 inches ought to have no less than 1024x768 resolution.(1)
    jpg-compress.com

    ReplyDelete
  16. This and considerably more can be accomplished by quality clipping path services alongside numerous other picture altering methods.
    clipping path service provider

    ReplyDelete
  17. It is the explanation, most of us require particular kinds of images, and we moreover need the support of Image Editing Administrations which can help us in making assorted sorts of photograph influences. clipping path company

    ReplyDelete
  18. Excellent blog! You have done really good work. Eren Yeager Jacket

    ReplyDelete
  19. he most recent web crawler refreshes have as of late made obviously the less pictures you have on your site, the more Google will overlook you.free ai upscaler

    ReplyDelete
  20. Prior to getting into the bare essential, a definitive reality is, pictures look great.Overscale

    ReplyDelete
  21. Really a awesome blog for the freshers. Thanks for posting the information. Embark on a transformative academic journey with Ziyyara Edutech's world-renowned online tuition for Class 11.
    For more info Contact us: +91-9654271931, +971-505593798 or visit online tuition for 11th class

    ReplyDelete

Your comments are valuable for us !!!