Dockerizing a Node.js web app

Image for post
Image for post

The goal of this example is to show you how to get a Node.js application into a Docker container. The guide is intended for development, and not for production deployment. The guide also assumes you have a working Docker installation and a basic understanding of how a Node.js application is structured.

In the first part of this guide, we will create a simple web application in Node.js, then we will build a Docker image for that application, and lastly, we will instantiate a container from that image.

Docker allows you to package an application with its environment and all of its dependencies into a “box”, called a container. Usually, a container consists of an application running in a stripped-to-basics version of a Linux operating system. An image is a blueprint for a container, a container is a running instance of an image.

To get in-Depth knowledge on Nodejs you can Enroll for a live demo on Nodejs Online Training

Create the Node.js app

First, create a new directory where all the files would live. In this directory create a file that describes your app and its dependencies:

{
"name": "docker_web_app",
"version": "1.0.0",
"description": "Node.js on Docker",
"author": "First Last <first.last@example.com>",
"main": "server.js",
"scripts": {
"start": "node server.js"
},
"dependencies": {
"express": "^4.16.1"
}
}

With your new file, run . If you are using version 5 or later, this will generate a file which will be copied to your Docker image.

Then, create a file that defines a web app using the Express.js framework:

'use strict';

const express = require('express');

// Constants
const PORT = 8080;
const HOST = '0.0.0.0';

// App
const app = express();
app.get('/', (req, res) => {
res.send('Hello World');
});

app.listen(PORT, HOST);
console.log(`Running on http://${HOST}:${PORT}`);

In the next steps, we’ll look at how you can run this app inside a Docker container using the official Docker image. First, you’ll need to build a Docker image of your app.

Take your career to new heights of success with Nodejs Course

Creating a Dockerfile

Create an empty file called :

touch Dockerfile

Open the in your favourite text editor

The first thing we need to do is define from what image we want to build from. Here we will use the latest LTS (long term support) version of available from the Docker Hub:

FROM node:10

Next, we create a directory to hold the application code inside the image, this will be the working directory for your application:

# Create app directory
WORKDIR /usr/src/app

This image comes with Node.js and NPM already installed so the next thing we need to do is to install your app dependencies using the binary. Please note that if you are using version 4 or earlier a file will not be generated.

To learn more about Dockerizing a Node.js web app and other great features of Nodejs, you can Enroll for a live demo on NodeJS Certification

# 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

Note that, rather than copying the entire working directory, we are only copying the file. This allows us to take advantage of cached Docker layers. bitJudo has a good explanation of this here. Furthermore, the command, specified in the comments, helps provide faster, reliable, reproducible builds for production environments.

To bundle your app’s source code inside the Docker image, use the instruction:

# Bundle app source
COPY . .

Your app binds to port so you'll use the instruction to have it mapped by the daemon:

EXPOSE 8080

Last but not least, define the command to run your app using which defines your runtime. Here we will use to start your server:

CMD [ "node", "server.js" ]

Your should now look like this:

FROM node:10

# Create app directory
WORKDIR /usr/src/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 8080
CMD [ "node", "server.js" ]

.dockerignore file

Create a file in the same directory as your with following content:

node_modules
npm-debug.log

This will prevent your local modules and debug logs from being copied onto your Docker image and possibly overwriting modules installed within your image.

Building your image

Go to the directory that has your and run the following command to build the Docker image. The flag lets you tag your image so it's easier to find later using the command:

docker build -t <your username>/node-web-app .

Your image will now be listed by Docker:

$ docker images

# Example
REPOSITORY TAG ID CREATED
node 10 1934b0b038d1 5 days ago
<your username>/node-web-app latest d64d3505b0d2 1 minute ago

Run the image

Running your image with runs the container in detached mode, leaving the container running in the background. The flag redirects a public port to a private port inside the container. Run the image you previously built:

docker run -p 49160:8080 -d <your username>/node-web-app

Print the output of your app:

# Get container ID
$ docker ps

# Print app output
$ docker logs <container id>

# Example
Running on http://localhost:8080

If you need to go inside the container you can use the command:

# Enter the container
$ docker exec -it <container id> /bin/bash

Test

To test your app, get the port of your app that Docker mapped:

$ docker ps

# Example
ID IMAGE COMMAND ... PORTS
ecce33b30ebf <your username>/node-web-app:latest npm start ... 49160->8080

In the example above, Docker mapped the port inside of the container to the port on your machine.

Now you can call your app using (install if needed via: ):

$ curl -i localhost:49160

HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: text/html; charset=utf-8
Content-Length: 12
ETag: W/"c-M6tWOb/Y57lesdjQuHeB1P/qTV0"
Date: Mon, 13 Nov 2017 20:53:59 GMT
Connection: keep-alive

Hello world

We hope this article helped you get up and running a simple Node.js application on Docker.

Written by

digital marketer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store