Dockerize your node.js app

Ankit Bavadiya
5 min readJan 6, 2022
Docker + Nodejs
  • Docker client: this is what’s running in our machine. It’s the docker binary that we’ll be interfacing with whenever we open a terminal and type `$ docker pull` or `$ docker run`. It connects to the Docker daemon which does all the heavy-lifting, either in the same host (in the case of Linux) or remotely (in our case, interacting with our VirtualBox VM).
  • Docker daemon: this is what does the heavy lifting of building, running, and distributing your Docker containers.
  • Docker Images: docker images are the blueprints for our applications. Keeping with the container/lego brick analogy, they’re our blueprints for actually building a real instance of them. An image can be an OS like Ubuntu, but it can also be an Ubuntu with your web application and all its necessary packages installed.
  • Docker Container: containers are created from docker images, and they are the real instances of our containers/lego bricks. They can be started, run, stopped, deleted, and moved.
  • Docker Hub (Registry): a Docker Registry is a hosted registry server that can hold Docker Images. Docker (the company) offers a public Docker Registry called the Docker Hub which we’ll use in this tutorial, but they offer the whole system open-source for people to run on their own servers and store images privately.

Need to install docker on your local machine. Here is a full guideline

  1. Setup nodeJS APP

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

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

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

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

'use strict';

const express = require('express');

// Constants
const PORT = 5000;
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.

2. Create Dockerfile

Create an empty file called Dockerfile:

touch Dockerfile

Open the Dockerfile in your favorite text editor

Your Dockerfile should now look like this:

FROM node:16# 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 5000
CMD [ "node", "server.js" ]

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 16 of node available from the Docker Hub

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

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 npm binary. Please note that if you are using npm version 4 or earlier a package-lock.json the file will not be generated.

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

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

Your app binds to port 5000 so you'll use the EXPOSE instruction to have it mapped by the docker daemon. If you set expose on TCP then use EXPOSE 5000/tcp

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

3. .dockerfile(optional)

Create a .dockerignore file in the same directory as your Dockerfile with the 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 Dockerfile and run the following command to build the Docker image. The -t flag lets you tag your image so it's easier to find later using the docker images command:

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

Your image will now be listed by Docker:

$ docker images# Example
REPOSITORY TAG ID CREATED
node 16 3b66eb585643 5 days ago
<your username>/node-web-app latest d64d3505b0d2 1 minute ago

Run the image

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

docker run -p 8000:5000 -d <your username>/node-docker-app

Print the output of your app:

# Get container ID
$ docker ps
# Print app output
$ docker logs <container id>
# Example
Running on http://localhost:5000

If you need to go inside the container you can use the exec 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 ... 8000->5000

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

Now you can call your app using curl (install if needed via: sudo apt-get install curl):

$ curl -i localhost:8000HTTP/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

--

--

Ankit Bavadiya

Backend developer, Actively working in ML and Chatbot development. DevOps is my practicing throughout life cycle of various project.