"Dockerizing" a Node.js Application

"Dockerizing" a Node.js Application

Daily short news for you
  • Manus has officially opened its doors to all users. For those who don't know, this is a reporting tool (making waves) similar to OpenAI's Deep Research. Each day, you get 300 free Credits for research. Each research session consumes Credits depending on the complexity of the request. Oh, and they seem to have a program giving away free Credits. I personally saw 2000 when I logged in.

    I tried it out and compared it with the same command I used before on Deep Research, and the content was completely different. Manus reports more like writing essays compared to OpenAI, which uses bullet points and tables.

    Oh, after signing up, you have to enter your phone number for verification; if there's an error, just wait until the next day and try again.

    » Read more
  • I just found a quite interesting website talking about the memorable milestones in the history of the global Internet: Internet Artifacts

    Just from 1977 - when the Internet was still in the lab - look how much the Internet has developed now 🫣

    » Read more
  • Just thinking that a server "hiding" behind Cloudflare is safe, but that’s not necessarily true; nothing is absolutely safe in this Internet world. I invite you to read the article CloudFlair: Bypassing Cloudflare using Internet-wide scan data to see how the author discovered the IP address of the server that used Cloudflare.

    It's quite impressive, really; no matter what, there will always be those who strive for security and, conversely, those who specialize in exploiting vulnerabilities and... blogging 🤓

    » 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:

Premium
Hello

5 profound lessons

Every product comes with stories. The success of others is an inspiration for many to follow. 5 lessons learned have changed me forever. How about you? Click now!

Every product comes with stories. The success of others is an inspiration for many to follow. 5 lessons learned have changed me forever. How about you? Click now!

View all

Subscribe to receive new article notifications

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

Comments (0)

Leave a comment...