"Dockerizing" a Node.js Application

"Dockerizing" a Node.js Application

Daily short news for you
  • How I wish I had discovered this repository earlier. github/opensource.guide is a place that guides everyone on everything about Open Source. From how to contribute code, how to start your own open-source project, to the knowledge that anyone should know when stepping into this field 🤓

    Especially, this content is directly from Github.

    » Read more
  • Just the other day, I mentioned dokploy.com and today I came across coolify.io - another open-source project that can replace Heroku/Netlify/Vercel.

    From what I've read, Coolify operates based on Docker deployment, which allows it to run most applications.

    Coolify offers an interface and features that make application deployment simpler and easier.

    Could this be the trend for application deployment in the future? 🤔

    » Read more
  • One of the things I really like about command lines is their 'pipeline' nature. You can imagine each command as a pipe; when connected together, they create a flow of data. The output of one pipe becomes the input of another... and so on.

    In terms of application, there are many examples; you can refer to the article Practical Data Processing Using Commands on MTTQVN Statement File. By combining commands, we turn them into powerful data analysis tools.

    Recently, I combined the wrangler command with jq to make it easier to view logs from the worker. wrangler is Cloudflare's command line interface (CLI) that integrates many features. One of them helps us view logs from Worker using the command:

    $ wrangler tail --config /path/to/wrangler.toml --format json

    However, the logs from the above command contain a lot of extraneous information, spilling over the screen, while we only want to see a few important fields. So, what should we do?

    Let’s combine it with jq. jq is a very powerful JSON processing command. It makes working with JSON data in the terminal much easier. Therefore, to filter information from the logs, it’s quite simple:

    $ wrangler tail --config /path/to/wrangler.toml --format json | jq '{method: .event.request.method, url: .event.request.url, logs }'

    The above command returns structured JSON logs consisting of only 3 fields: method, url, and logs 🔥

    » 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

The secret stack of Blog

As a developer, are you curious about the technology secrets or the technical debts of this blog? All secrets will be revealed in the article below. What are you waiting for, click now!

As a developer, are you curious about the technology secrets or the technical debts of this blog? All secrets will be revealed in the article below. What are you waiting for, 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...
Scroll or click to go to the next page