"Dockerizing" a Node.js Application

"Dockerizing" a Node.js Application

Daily short news for you
  • Privacy Guides is a non-profit project aimed at providing users with insights into privacy rights, while also recommending best practices or tools to help reclaim privacy in the world of the Internet.

    There are many great articles here, and I will take the example of three concepts that are often confused or misrepresented: Privacy, Security, and Anonymity. While many people who oppose privacy argue that a person does not need privacy if they have 'nothing to hide.' 'This is a dangerous misconception, as it creates the impression that those who demand privacy must be deviant, criminal, or wrongdoers.' - Why Privacy Matters.

    » Read more
  • There is a wonderful place to learn, or if you're stuck in the thought that there's nothing left to learn, then the comments over at Hacker News are just for you.

    Y Combinator - the company behind Hacker News focuses on venture capital investments for startups in Silicon Valley, so it’s no surprise that there are many brilliant minds commenting here. But their casual discussions provide us with keywords that can open up many new insights.

    Don't believe it? Just scroll a bit, click on a post that matches your interests, check out the comments, and don’t forget to grab a cup of coffee next to you ☕️

    » Read more
  • Just got played by my buddy Turso. The server suddenly crashed, and checking the logs revealed a lot of errors:

    Operation was blocked LibsqlError: PROXY_ERROR: error executing a request on the primary

    Suspicious, I went to the Turso admin panel and saw the statistics showing that I had executed over 500 million write commands!? At that moment, I was like, "What the heck? Am I being DDoSed? But there's no way I could have written 500 million."

    Turso offers users free monthly limits of 1 billion read requests and 25 million write requests, yet I had written over 500 million. Does that seem unreasonable to everyone? 😆. But the server was down, and should I really spend money to get it back online? Roughly calculating, 500M would cost about $500.

    After that, I went to the Discord channel seeking help, and very quickly someone came in to assist me, and just a few minutes later they informed me that the error was on their side and had restored the service for me. Truly, in the midst of misfortune, there’s good fortune; what I love most about this service is the quick support like this 🙏

    » 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

Me & the desire to "play with words"

Have you tried writing? And then failed or not satisfied? At 2coffee.dev we have had a hard time with writing. Don't be discouraged, because now we have a way to help you. Click to become a member now!

Have you tried writing? And then failed or not satisfied? At 2coffee.dev we have had a hard time with writing. Don't be discouraged, because now we have a way to help you. Click to become a member 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...