/Dockerizing-a-NodeJS-web-app

A simple NodeJS application deploying on Docker Container

Primary LanguageDockerfileMIT LicenseMIT

Dockerizing-a-NodeJS-web-app

Node.js


Create a simple nodeJs application and deploy it onto a docker container.

  1. Create a working directory

    mkdir <working_directory_name>

  2. Running this command in working directory will initialize your project

    npm init

This will create a package.json file in the folder, that file contains app dependency packages.

Replace the following code of package.json

  // package.json

  {
    "name": "docker_web_app",
    "version": "1.0.0",
    "description": "Node.js deploy on Docker container",
    "author": "cmuth001@odu.edu",
    "main": "server.js",
    "scripts": {
      "start": "node server.js"
    },
    "dependencies": {
      "express": "^4.16.1"
    }
  }
  1. Running this command will install all the dependencies from package.json

    npm install

  2. Lets create a server.js file that defines a web-app using an Express framework.
   // server.js
   'use strict';
   var express = require('express');
   var app = express();
   app.get('/', function (req, res) {
     res.send('Hello World!');
   });
   app.listen(3000, function () {
     console.log('Example app listening on port 3000!');
   });
  1. Lets test the application, run the below command

    node server.js

If you followed the above steps on your system, you will see the same output as below image: http://localhost:3000/

Node.js

Now node.js app is running successfully.

Lets try running the same node.js application running on the docker container. To run the application on the docker conatiner we need a docker image.

First, we will create a docker image for the application.

  1. Create a Dockerfile

    touch Dockerfile

  2. Dockerfile should look like this
FROM node:10
# Create app directory
WORKDIR /usr/app

# Install app dependencies
# A wildcard is used to ensure both package.json AND package-lock.json are copied
# where available (npm@5+)
COPY package*.json ./

RUN npm install
# If you are building your code for production
# RUN npm ci --only=production

# Bundle app source
COPY . .
EXPOSE 3000
CMD [ "node", "server.js" ]

  1. Create .dockerignore file with following content
node_modules
npm-debug.log

This will prevent from copying onto docker image.

  1. Building Docker image

    docker build -t node-web-app .

    Node.js

  2. Check the Docker images

    docker images

    Node.js

  3. Run the docker image

    docker run -p 49160:3000 -d node-web-app

  4. Get the container id

    docker ps

    Node.js

  5. Lets know where it is running on

    docker logs <container_id>

output: 
    Example app listening on port 3000!
  1. If you followed the above steps on your system, you will see the sam output as below image: http://localhost:49160/

Node.js

I hope this tutorial helped you get up and running a simple Node.js application on Docker container.