Hello Dev,

Container technology is around for a while, but it becomes more popular when the arrival of this thing "Docker". Docker allows us to package our application with all dependencies together; which can be easy to ship to your multiple vm across. So this article is about how to deploy a hello world application using Nodejs + Container.


Create the Node.js app

Create a project folder and touch three files in it: a package.json file, server.js file and finally your Dockerfile, now start pasting the following code snippet in the corresponding files.

Package.json:

{
    "name": "docker_app",
    "version": "1.0.0",
    "description": "Node.js-Docker",
    "main": "server.js",
    "scripts": {
      "start": "node server.js"
    },
    "dependencies": {
      "express": "^4.16.1"
    }
}

server.js:

'use strict';

const express = require('express');

// Constants
const PORT = 8080;

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

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

Dockerfile:

FROM node:8
#creating app directory
WORKDIR /usr/src/app

COPY package*.json ./
RUN npm install

COPY . .

EXPOSE 8080
CMD [ "npm", "start" ]

Now build your app using the below command:

Building your image

$ docker build -f Dockerfile .

To run the docker container use command:

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 49160:8080 -d dockerfile

The following are the command to see running instances and logs

# to all containers and using to get container pid
$ docker ps

# to see docker log
$ docker logs <container id>
output
Running on http://localhost:8080

Happy coding! 🙌