Guide
March 28th

Docker Nodejs Socket.io tutorial. Dockerize nodejs app in 3 minutes.

This is a brief tutorial that presents how you can run a simple NodeJS/Sockert.io Chat application in Docker.

Requirements

Before you start, you need to have some certain prerequisites in place:

  • Node v10.15.2+
  • npm 6.4.1+

You can run the following command to check the node version:

node --version
npm --version

Step 1 - Set Up Your NodeJS application

Let's build a simple chat application as example. We will use NodeJS for the backend side and Socket.io for real-time two-way communication.

1. Configure your project

To initialize a NodeJS project, just run the following command on your terminal:

npm init

To use ES6 in your project, you need to configure babel. So let's install it and also install nodemon for development server. So put the following object in the package.json file.

"devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-stage-0": "^6.24.1",
    "nodemon": "^1.15.0"
}

Then, to install the dependencies just run:

npm install

In the project root, make one file called .babelrc.

{
   "presets": [
     "es2015", "stage-0"
   ]
}

Okay, now create the main file called server.js inside project root. Also, add the start script inside the package.json file.

"scripts": {
    "start": "nodemon ./server.js --exec babel-node -e js"
}

2. Install express and start the server

Install the packages by typing the following command in your terminal:

npm install express body-parser --save

Then, set up the express server putting the following code in server.js file:

// server.js

import express from "express";
import path from "path";
import bodyParser from "body-parser";

const app = express();

3. Install Socket.io library

To install socket.io just run the following command:

npm install express body-parser --save

Now, create a server.

// server.js

import express from "express";
import path from "path";
import bodyParser from "body-parser";

const app = express();
const server = require("http").createServer(app);
const io = require("socket.io").listen(server);
const PORT = 3000;
server.listen(PORT);
console.log("Server is running");

app.get("/", (req, res) => {
  res.sendFile(__dirname + "/index.html");
});

Here, you have created a server variable and pass the express application in it. Then, you have connected the socket.io to the server. So when any client sends any request, then it directly listens to that event. Also, create a file called index.html inside the root folder.

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <meta http-equiv="X-UA-Compatible" content="ie=edge">
   <title>Node.js Socket.io Chat Application</title>
   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
   NodeJs-Socket.on app running successfully!!!
   <script  data-src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js" type="text/js"></script>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js" type="text/js"></script>
</body>
</html>

Now, to start your server, hit the following command at the root of the project: npm start. As you should see on http://localhost:3000 your server is running correctly.

header image

4. Create a form to enter the message

The next step is create a chat area for your application, just set the following code on the index.html file.

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <meta http-equiv="X-UA-Compatible" content="ie=edge">
   <title>Node.js Socket.io Chat Application</title>
   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
   <div class="container">
      <h1 class="jumbotron">
         NodeJS - Socket.io Chat Application
      </h1>
      <div class="row" style="margin-top: 70px;">
         <div class="col-md-4"></div>
         <div class="col-md-6">
            <div id="chatArea">
            </div>
            <form id="myForm">
               <div class="form-group">
                  <textarea rows="5" id="txt" cols="5" class="form-control"></textarea>
               </div>
               <div class="form-group">
                  <button type="submit" class="btn btn-success">Send</button>
               </div>
            </form>
         </div>
      </div>
   </div>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js"></script>
</body>
</html>

5. Make a socket connection

First of all, you need to make connections array to track the connections in your application. So, type the following code on your server.js file.

// server.js

const connections = [];

io.sockets.on("connection", socket => {
  connections.push(socket);
  console.log(" %s sockets is connected", connections.length);

  socket.on("disconnect", () => {
    connections.splice(connections.indexOf(socket), 1);
  });
});

Now, only one thing is remaining, and that is to connect the socket to the client. So in an index.html page, write the following code.

<script>
   jQuery(document).ready(function() {
         var socket = io.connect();
   });
</script>

So here, we are trying the connect with the socket. If the socket is connected, then we can find its length on the server. Now we can emit the messages back and forth, and we can get the messages real time. Now open the browser window on http://localhost:3000. You can do it on multiple windows, and you can see in the console that more and more sockets are being connected.

6. Listen to the send message event

From the client side we have connected to the socket. Now, we need to create an event and send our chat message in that event. So let us emit an event with our chatbox message.

<script>
  jQuery(document).ready(function() {
     var socket = io.connect();
     var form = jQuery('#myForm');
     var txt = jQuery('#txt');
     var chatArea = jQuery('#chatArea');

     form.submit(function(e) {
        e.preventDefault();
        socket.emit('sending message', txt.val());
        txt.val('');
     })

     socket.on('new message', function(data){
         chatArea.append('<div class="well">'+data.message+'</div>');
     });
  });
</script>

So it is just a basic jquery. We have connected to the socket so just fire an event called sending a message. The server will listen to that event, and we can broadcast it to other clients. So on server.js add the following code:

socket.on("sending message", message => {
  console.log("Message is received :", message);

  io.sockets.emit("new message", { message: message });
});

7. Run the project

Finally just run npm start, you will see the following screen:

header image

Step 3 - Dockerize the Application

Setup Docker

Before creating a container for the Django application and shipping it off, you need to install Docker on your local machine. For learning purpose, you will install Docker Community Edition. Select your OS from the list below and follow the setup instructions;

Make the docker App image

The next stage is adding a Dockerfile to your project. The structure of a Dockerfile can be considered a series of instructions on how to build your container/image.

Start the Dockerfile by creating an empty file named Dockerfile in the root of your project. Then, complete each instruction according to the following example:

# Dockerfile
FROM node:10.15.2

WORKDIR /app

COPY . /app

RUN npm install

EXPOSE 3000
CMD npm start

Building and Running the Container

Building the container is very straight forward once you have Docker and Docker Machine on your system. The following command will look for your Dockerfile and download all the necessary layers required to get your container image running. Afterwards, it will run the instructions in the Dockerfile and leave you with a container that is ready to start.

To build your docker container, you will use the docker build command and provide a tag or a name for the container, so you can reference it later when you want to run it. The final part of the command tells Docker which directory to build from.

$ docker build -t node-socket-tutorial .

The final step is to run the container you have just built using Docker:

$ docker run -it -p 3000:3000 node-socket-tutorial

The command tells Docker to run the container and forward the exposed port 3000 to port 3000 on your local machine. After you run this command, you should be able to visit http://localhost:3000 in your browser.

You can see the Docker containers that are currently running on your system (along with their Container IDs) with:

$ docker ps -a

To turn off your Docker container, run:

$ docker stop container_id

Step 4 - Push to cloud

1. Create your app

In order to deploy your docker container, just create a new app via cli or admin panel and set a port to 3000.

header image

2. Push your docker container

header image

3. Set up resources

header image

4. Logs and app status

header image

5. Release

After release the app, you can access into the app using the generated URL: header image

header image

Now you can deploy your NodeJS app without a massive build time.

Bonus 1: SSL certificate for HTTPS

It's already done for you. If you need to connect your custom domain, SSL certificate will be provided for it.


Bonus 2: Autoscaling

With autoscaling the app will be scaled up when CPU and RAM load goes up and scaled down when it goes down.

Now you can deploy your NodeJS Socket app without a massive build time.

Dockerize your Job

Just for $2/month
Share this article:

Ask a question

Please type your name.
Please provide your email address.
Please tell us a bit more

More great guides

Docker nodejs express tutorial

Docker NodeJS Express guide

Simple Nodejs Socket guide for docker deploy. Use it for comfort start with us.

Read Guide
Docker python django tutorial

Docker Python Django tutorial

This is a brief tutorial that presents how you can run a simple 'Hello World'-style web application written in Django in docker.

Read Guide
Docker PHP laravel tutorial

Docker PHP laravel tutorial

This quickstart guide provides a basic introduction to the Laravel framework running on docker. This is a great starting point if you are brand new to the Laravel framework or if you want to have your docker PHP app.

Read Guide
7 times faster deployment
Dockerize automaticaly completes deployment after receiving your Docker image
50% of AWS price
We don’t have any hidden prices and will never ask you to pay extra fee for our services
Open Sidebar Close Sidebar