Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / containers / docker

Getting started on Docker with Windows and hosting Nodejs App inside a container

5.00/5 (5 votes)
24 Oct 2016CPOL11 min read 40.7K   152  
Getting started on Docker with Windows OS and Hosting nodejs app inside a container

Introduction

In this article we will look into how quickly we can configure docker on windows OS and host a nodejs app inside a docker container. Also we will walkthrough some of the commands required to configure docker container. This article will be divided into two sections, first section will cover installing and running docker service on windows OS and second section will cover mounting nodejs code inside a docker container and running it. For understanding second section you will require some basic understanding of nodejs & npm.

I would like to get feedback on this article. Please feel free to share your comments or you can also email me at shettyashwin@outlook.com. If you like this article, please don't forget to rate it.

Background

We were facing couple of challenges with our build server when two builds were triggered at same time especially with angularjs and nodejs app. Also we were looking for smart options to release code changes more frequently in production. So we started looking at micro services and other options for parallel build, plus we were also looking for quick but less error prone techniques when it comes to deployment of services. Rolling back new changes in case of any issue was also something we needed. Our application is been developed on .net and development is been done over a period of time. Moving out of windows OS was never on card. Idea was to get all new services on to micro services  with new upcoming technology like Nodejs, Angularjs etc.

Finally we decided on to docker. But getting up and running on windows 7 was bit complicated comparing to windows 10 (with hyper-v). In below article I will share step by step configuration to configure docker on windows 7 using docker toolbox and windows 10 (with hyper-v) using docker installer.

Prerequisites

You can check here if your OS has Hyper-V

Windows OS without Hyper-V 

Virtualization should be enabled in bios. Click here for details to enable virtualization in bios.

Docker Toolbox setup.

Windows OS with Hyper-V

Docker Installer. Hyper-V needs to be enabled before Docker installer is been executed.

 

Lets get started 

Windows OS without Hyper-V 

Execution of docker tollbox setup is pretty simple and straight forward. Once you sucessfully install docker toolbox (non hyper-v) you should have 3 icons on your desktop.

Docker-CLI Kitematic VM-Virtual

I would highly recommend to launch all the shorts in admin privileges. This will avoid unnecessary issue.

Let’s get started, double click on Docker QuickStart Terminal. Since you are running docker for the first time it will download boot2docker and apply necessary setting to get you started. It will take few minutes depending upon your system processing power and network bandwidth. Once everything is successfully up and running you should be able to see below image.

Docker Welcome Screen

Please make a note of IP address in the welcome screen. We will need this to access application hosted inside docker container. Docker quick starter will create default VM which we will use to run our sample application.  Ok now we are ready with the docker instance which we can play around. But if you are planning to mount (not copy) some of the local system files into docker you will have to first execute few commands. This commands are only required if you are running docker with toolbox. Following command will map your local folder to docker VM and from VM to container.

Open a new command prompt with admin privileges and type following command.

BAT
docker-machine stop default

In the above command we are shutting down our default VM machine for docker. If Command prompt is not able to recognize docker-machine, please check if installed docker folder (inside program files) is added to PATH environment variable. If it is not added by installer, please go head and add the same. Detail’s for updating PATH variable is available here. While updating path variable please make sure you are considering your system path.

I have created RD folder on my system’s D drive. These folders will have all my code and folder to hold application Database files. I will be mounting D:\RD to VM.

BAT
VBoxManage.exe sharedfolder add default --name "/d/rd" --hostpath "\\?\d:\RD" --automount

Now let’s quickly see what does above command mean. 

default : Name of the  VM in which we wish to share this folder

--name : Name ('/d/rd') by which we will refer hostpath inside docker VM.

--hostpath :  path ('\\?\d:\RD') which is getting mapped.

--automount : to keep mounting this drive on every VM restart.

If command prompt is unable to find VBoxManage.exe than navigate to C:\Program Files\Oracle\VirtualBox (path depends on which drive you have installed docker toolbox) from command prompt and try again. On sucessfull execution run below command. This will start docker VM 

BAT
docker-machine start default

Now we have mapped local system folder to docker VM, but to access this folder inside docker container we will have to first connect this to docker VM, create a folder inside VM and mount host system folder to VM Folder. Note that files inside D:\RD (host shared folder) will only be accessible based upon privilege in which you have started docker VM. For safer side, I have given EVERYONE read/write access to this folder. I do not recommend giving EVERYONE access to your folder, you can decide what access needs to be given based upon your project requirement. To connect docker VM you can execute below command.

BAT
docker-machine ssh default

Above command will make secure connection to default VM. Next step to create a folder in VM and mount local drive to it. Please execute below 2 commands.

BAT
sudo mkdir --parents /d/rd

This will will create a folder inside Docker VM

BAT
sudo mount -t vboxsf /d/rd /d/rd

This will mount key name '/d/rd/' to folder we just created. In the mount command mentioned above, first /d/rd represent name key which we create while executing VBoxManage command and Second /d/rd represent folder name we just created inside Docker VM. Type exit and move out of docker VM. Now to point your command prompt to default docker instance, execute following command.

BAT
 @FOR /f "tokens=*" %i IN ('docker-machine env default') DO @%i

This will set default value to your command prompt in silent mode. If wish to see this value you can execute docker-machine env default,  this will list all the parameter for future reference.

If you wish to change RAM or CPU for your docker VM / Container you can set it using Oracle VM Virtualbox. Look for System tab under default VM. Image for reference below. Both the setting can only be changed when VM is not running.

Oracle VM Manager, System Setting

Windows OS with Hyper-V 

Installation of Docker on OS with Hyper-V is pretty simple. After successful installation you should see docker icon in your notification Area. To change CPU / RAM / Drive Mounting, just right click on this icon and using setting from the menu.

Docker Setting

Docker Image

Since we are planning to deploy nodejs application using Docker, we will be using nodejs recommended image for docker. If you are running docker on non Hyper-V OS make sure you have set environment variable for command prompt or execute below command in docker cli which you get after launching Docker Quick Start

You can either download Nodejs recommend image in advance by using pull command else docker will attempt to download this image when you execute build or run command. For simplicity we will download image in advance.

BAT
docker pull node:argon

This will download node:argon  from docker hub to local registry. While building any image docker first refers to local registry, only if it is not available locally it will download it from docker hub. If you wish to try some other images you can search it here 

Building Docker image for Production / Build Environment

Let’s assume for running your nodejs app you have some prerequisite which needs to be preinstalled before your app gets started. To demonstrate nodejs example below I will be using Expressjs and NodeMon. Expressjs will host and serve http request and nodemon will monitor changes in source code. Now let us create an image which has expressjs and Nodemon preinstalled.

Before we get started let us create a folder structure we will be using in our app development. I will be creating RD folder on my D Drive. RD folder will again have two folders inside it, docker and service. To build our image we will be using docker folder (D:\RD\docker). Now create new file with name Dockerfile. Please note this file should not have any extension. Now open this file inside notepad or any other text editor you are comfortable with and below source code.

BAT
FROM node:argon
MAINTAINER Ashwin Shetty <shettyashwin@outlook.com>

RUN "apt-get update && apt-get clean"
RUN npm install -g express
RUN npm install -g nodemon

# Create app directory
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app

EXPOSE 9000

Line 1 : From node:argon will tell docker engine to refer node:argon image from the registry. If you have not downloaded node:argon image it will try to download it again 

Line 2 : MAINTAINER Ashwin Shetty <shettyashwin@outlook.com> is non mandatory, I would still recommend this to be added in your dockerfile to keep a note of maintainer.

Line 4  / 5 / 6: RUN ""  this will run all your command while creating a base image. apt-get update && apt-get clean takes the latest update based upon OS and then clears the temp folder. npm install will install express and nodemon globally inside this image.

Line 8 & 9 : mkdir & WORKDIR will create empty folder and mark this directory as a working folder.

Line 11 : EXPOSE  will expose port 9000 from container. We will require this  to access application from a container.

Now let’s build this image. Open a command prompt and navigate to D:\RD\docker folder. Execute following command inside your command prompt.

BAT
@FOR /f "tokens=*" %i IN ('docker-machine env default') DO @%i
docker build -t dockerApp .

Line 1 : will set variable which will be refered by docker exe to docker instance (only required in Non Hyper-v system)

Line 2 : will create docker image with name dockerApp, please do not miss to add dot at the end of your command. This will let docker engine know where to look for dockerfile.

Once you have successfully executed above command, you should be able to see dockerApp image in docker image registry locally. To see local docker registry you execute following command

BAT
docker images

Sample Nodejs App

For creating nodejs service, create server.js file inside D:\RD\service and below code.

JavaScript
var express = require('express')
var app = express()
 
app.get('/', function (req, res) {
  res.send('Hello World')
})
 
app.listen(9000)

Source Code Refered from : - https://www.npmjs.com/package/express 

Above code will host API which will return Hello World when you hit http://[docker ip / localhost]:9000

Running App inside a container 

Ok now we are done with all the heavy lifting and it’s time to see final output from a docker container. Execute following command in your command prompt

BAT
docker run -i  --name nodeservice -p 9000:9000 -v /d/rd:/usr/src/app dockerApp /bin/bash/ -c 'cd service; nodemon server.js'

docker run command will start a new container process using parameters we just passed. Let me quickly explain the parameters,

--name : will define name of the container process, we have named it nodeservice 

-p : will let docker know to expose port 9000 and map it to local system port 9000.

-v : will mount local system folder D:/rd inside docker container. Please note we have used /d/rd in above command, /d/rd is the mapping which we have created inside docker VM. We are mapping /d/rd  to container directory /usr/src/app which we have created while creating dockerapp image. Refer to mkdir command in Dockerfile

dockerApp : is the name of image which will be used for running this instance.

-c : command mentioned here will be executed by docker-engine. In the above command we are navigating to service folder and then running server.js using nodemon. 

If you wish to run command manually than replace –i  with –it, this is how your command should look like. Below command will run container in interactive mode.

BAT
docker run -it --name nodeservice -p 9000:9000 -v /d/rd:/usr/src/app dockerApp /bin/bash/

If you are running docker run multiple time you might see few error mentioning container are already present. To see all the running container or its history you run below command

BAT
docker ps -a

and to remove already dead container you can use 

docker rm dockerApp

Now if you running container on Non Hyper-V system, use docker machine IP with port 9000 to see response from node service hosted inside container. If you are using machine with Hyper-V use local IP with port 9000 to see output.

You can also use Kitematic to view all running app, pulled images, Kill / Start / Stop Containers, Exposed Port / UI and Environment variable. But as a developer I feel more confident and simple to execute all the command and configurations using CLI

Points of Interest

Using a container based technology like docker it becomes more simple and fast to create or recreate an environment which can shipped or shared. Using docker hub we can explore may technologies which are preconfigured. This drastically reduces configuration time, just to give an idea using docker we were able run tensorflow (AI from google) in 20 mins. 

I have attached Docker File and Server.js for you to play around. Please feel free to share your feedback or suggestion.

Reference

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)