Let’s have a simple NodeJS "Hello World" web service that listens on port 8088 and greets you on GET request.

Example NodeJS app

I have a NodeJS application located in <workspace>/hello-docker.

The NodeJS package is described by a following package.json created by calling npm init and then installing the express dependent library:

hello-docker/package.json
{
  "name": "hello-docker",
  "version": "1.0.0",
  "description": "Simple demonstration of dockerization",
  "main": "main.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "korimsoft",
  "license": "",
  "dependencies": {
    "express": "^4.17.1"
  }
}

There is also a corresponding package-lock.json file created.

hello-docker/main.js
#!/usr/bin/env node

const PORT = 8088;

const app = require('express')();
const http = require('http');


app.get('/', (req, res) => {
    res.status(200).send("Hello!\n");
})

const server = http.createServer(app);

server.listen(PORT, ()=>{
    console.log(`Listening on ${PORT}`);
});

Now, we would like to run this service in a Docker container. What do we do? What do we need?

Creating a Dockerfile

Docker container is described by Dockerfile. It is basically a cookbook for containerizing the project. We typically specify:

  • Which container is used as base (NodeJS in our case).
  • What files should be copied from the local machine and where to in the container.
  • What commands should be run inside the container (preparation, installation, ...).
  • What TCP/UDP ports should be exposed outside the container.
  • And many more - see the Dockerfile Reference

Here is the Dockerfile for the hello-docker project

hello-docker/Dockerfile
from node:latest

# Installing the application
# Working directory inside the container
WORKDIR /helloapp

COPY package.json ./
COPY package-lock.json ./

RUN npm install

# Copy the source code to the working directory
COPY main.js .

#Expose the port
EXPOSE 8088

#Start the application
CMD ["node", "main.js"]

Building and Running the Container

To build the container, go to the directory where the Dockerfile is located and run

Building the container
hello-docker/$ docker build -t korimsoft/hello-docker .

This will build a container with tag korimsoft/hello-docker. And now, finally, we can run the container with

Running the Container
$ docker run -p 8088:8088 -d korimsoft/hello-docker

To prove that the application works, either open the web browser on localhost:8080 or call curl localhost:8080 from the command line. You should get your Hello.

Docker run, again, has a lot of parameters that could (and should) be tinkered around with. See its documentation