"Dockerizing" a Node.js Application

"Dockerizing" a Node.js Application

Daily short news for you
  • Good news to start the day. GitHub has just widely announced GitHub Models to everyone. If you remember, more than 2 months ago, GitHub had a trial program for using LLMs models, and in my case, it took a month to get approved for use. Now, they have given everyone with a GitHub account access, no registration needed anymore 🥳

    GitHub Models is currently a lifesaver for me while building this blog 😆

    GitHub Models is now available in public preview | Github Blog

    » Read more
  • I came across a repository that uses Tauri and Svelte to rewrite an application like the Task Manager on Windows or the Monitor on Mac. I was curious, so I downloaded it and was surprised to find that the app is only a few MB in size and loads quickly. The app itself is also very smooth

    » Read more
  • I've noticed that whenever I'm enthusiastic about reading, I tend to be lazy about writing. This week, I'm reading three books at the same time, or rather, two and listening to one.

    The most haunting book so far is 'The Black Ocean' - a collection of 12 stories about people struggling with depression. I have a strong mental fortitude, but after reading just two stories, I felt suffocated and restless.

    The next story brought some relief, as the protagonist managed to control their emotions. However, as I continued reading, I felt like I was being choked again. It's terrifying, and I couldn't close my eyes while listening.

    One sentence that particularly resonated with me is when the parents of someone struggling with depression ask why they're like that, and the person responds, 'How am I supposed to know? It's like asking someone why they're sick. Nobody wants to be like that!'

    » Read more

The Issue

There are many ways to deploy a Node.js application in practice. The simplest one is just running the node index.js command to start it. However, to keep the application running continuously, we need a process management tool, such as pm2.

Using pm2, we can initialize a Node process and keep it running continuously until intentionally stopped. Furthermore, it enables us to scale the application from 1 instance to 2, 3, 4... instances, as long as your server can handle it. pm2 also offers many other features that you can explore in its documentation.

Recently, the terms "Dockerize" or "Containerize" have gained traction in the online community. In simple terms, it involves "packaging" the application into a single "file" known as an Image. Once an application is packaged, it can be launched with Docker using just a few commands.

To better understand this, let's imagine the steps for deploying a Node application on a server. First, we need to install Node.js, clone the source code, install dependencies with npm install, run npm run build if required, set up environment variables (e.g., in a .env file), and finally use pm2 to start the application. This involves several steps, and for more complex applications, the process may be longer. Additionally, if any step encounters an error, it can lead to a troubleshooting process. By "containerizing" your application, you can significantly streamline this process. You may only need 2 steps: pulling the Image and using Docker or any container management tool to start it.

Moreover, the process of "Dockerizing" ensures the "consistency" of your application across various environments. For example, after Dockerization, you can use the same Image to start the application on Windows, Linux/Unix, Mac, etc., with little concern for specific environment configurations.

There is much to explore if you are new to this, so this article is a guide to Dockerizing a Node.js application and running it with Docker as simply as possible. It is hoped that through this article, readers can visualize a process for Dockerizing an application, laying the foundation for delving deeper into the details later on.

Creating a Dockerfile

A Dockerfile is a text file that instructs Docker on how to create an Image. From this Image, a container can be initialized to run the application.

Assuming your current application directory is /src/my-app, where the package.json file looks like this:

{
  "name": "my-node-app",
  "version": "1.0.0",
  "description": "Node.js on Docker",
  "author": "First Last <[email protected]>",
  "main": "index.js",
  "scripts": {
    "start": "node index.js"
  },
  "dependencies": {
    "express": "^4.16.1"
  }
}

And there is an index.js file to initialize an HTTP server on port 8080:

'use strict';

const express = require('express');

// Constants
const PORT = 8080;
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}`);
});

Running node index.js will display the following output in the console:

$ node index.js
Running on http://0.0.0.0:8080

Create a Dockerfile with the following content:

FROM node:16

WORKDIR /usr/src/app

COPY package*.json ./

RUN npm install

COPY . .

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

If you find each line of content unfamiliar, you may need to read more basic knowledge about Dockerfile or refer to Creating a Dockerfile for guidance.

Building the Docker Image

Once you have a Dockerfile, you can use Docker to build an Image. It's straightforward—navigate your terminal to the directory containing the Dockerfile and use the build command:

$ docker build . -t my-node-app

Replace my-node-app with a name of your choice for the Image.

Running the Application from the Image

Finally, try launching your application with Docker using the run command. Using the -d flag will run your application in the background, ensuring it continues running even after you exit the terminal:

$ docker run -p 8080:8080 -d my-node-app

To view the application's logs:

$ docker logs my-node-app
Running on http://localhost:8080

You can use curl to call http://localhost:8080 to see the result:

$ curl http://localhost:8080
Hello World

Stopping the Application

You can also easily stop the application using the kill or stop command:

$ docker kill my-node-app
# or
$ docker stop my-node-app

Conclusion

"Dockerizing" a Node.js application involves packaging your application into an Image to make it easy for container management tools to start and manage. This reduces the number of steps involved in deployment and automation processes. Additionally, it simplifies the process of setting up the runtime environment on different platforms, such as Windows, Linux/Unix, Mac, etc.

References:

or
* The summary newsletter is sent every 1-2 weeks, cancel anytime.
Author

Hello, my name is Hoai - a developer who tells stories through writing ✍️ and creating products 🚀. With many years of programming experience, I have contributed to various products that bring value to users at my workplace as well as to myself. My hobbies include reading, writing, and researching... I created this blog with the mission of delivering quality articles to the readers of 2coffee.dev.Follow me through these channels LinkedIn, Facebook, Instagram, Telegram.

Did you find this article helpful?
NoYes

Comments (0)

Leave a comment...