Setup Node.js app with Docker

Docker is the most popular tool to create, deploy and run any application easily by using containers. Today we will learn how to set up Node.js in Docker. We will start with a very basic Hello Docker program.

Photo by frank mckenna on Unsplash

Requirements

  • Docker
  • Node.js
  • express

Node.js Application

To start with node first create a package.json file.

npm init -y

Above command will create a black package.json file in your root working directory. After that, we have to install the express framework.

npm i express
{
  "name": "web-app",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "start": "node server.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1"
  }
}

Now create a server.js file at your project root directory and just copy and paste the below codes. These codes will only send the Hello Docker message to the client (browser).

'use strict';

const express = require('express');

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

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

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

Setup Docker for Node.js

Now let’s move to the Docker setup section. You should remain in the same working directory and create a file with the name Dockerfile and add the following codes into the Dockerfile.

FROM node:10

# Create app directory
WORKDIR /usr/src/app

# Copy app dependencies
COPY package*.json ./

# Install app dependencies
RUN npm install

# Bundle app source
COPY . .

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

As you see in the Dockerfile, we have used the official Node.js image to setup Node.js and NPM. The WORKDIR will create a directory on the given location. Now we have to copy our package.json and package-lock.json file on the created location. For doing this we have to use the COPY command. After that, we have to install our dependencies and for that, we are using RUN npm install.

And COPY . . command will copy your entire project into the container for the build. The EXPOSE is used to define a port that will use to run the project and we have used the 8080 port. And in the very last line we have to run our application and for that we have used CMD [“node”, “server.js”]

Now it’s time to building your own image. We have to run the following command to create a Docker image. The -t flag will help you to tag your image, so that it will easy to later by using Docker images command.

docker build -t [tag_name]/docker-node-app .

Now run the docker images command and you see that your image will appear on the list.

Run the Docker image

docker run -p 8080:8080 -d [tag_name]/docker-node-app

The -d option will run the container in detached mode and the -p option is used to define the port.

Now visit the http://locathost:8080 to verify if the app is running successfully.