DEV Community

Cover image for How To Set Up Docker In Nodejs
David Chibueze Ndubuisi
David Chibueze Ndubuisi

Posted on

How To Set Up Docker In Nodejs

Introduction

Have you ever found yourself feeling exhausted from repeatedly going through the same tedious process of setting up your development environment? You know, installing and configuring all the necessary software, libraries, and tools required to get your application up and running? And let's not forget the headache of dealing with software dependencies - making sure that all the components of your application work together seamlessly. And then there's the stress of wondering whether your application will work on different machines and operating systems, leaving you constantly worrying about compatibility issues. Does this sound familiar? If so, then you're in luck!

If you're tired of the endless cycle of setting up development environments, dealing with software dependencies, and worrying about application compatibility, then Docker is the solution you've been looking for.

Before we dive into the details of setting up Docker in Node.js, let's take a step back and answer a basic question: what is Docker, exactly? Understanding the fundamentals of Docker will help you get the most out of this article and the technology itself. So in this section, we'll explore the basics of Docker, including what it is, how it works, and its benefits.

What is Docker?

Docker is a containerization technology that allows you to package an application and its dependencies into a single, lightweight, and portable container. In other words, it's a tool that makes it easier to build, ship, and run distributed applications.

Unlike virtual machines, which require a complete operating system to be installed, Docker containers use the host machine's operating system kernel and share system resources, making them more efficient and lightweight. This means that Docker containers can run on any machine with Docker installed, regardless of the operating system or hardware.

Docker provides a number of benefits, including simplified deployment, improved portability, and increased compatibility. By packaging your application and its dependencies into a container, you can ensure that it runs consistently across different environments, without worrying about the underlying system configuration.

Now that you have a basic understanding of what Docker is and how it works, let's dive into the specifics of setting up Docker in Node.js. In the following sections, we'll cover everything you need to know to get started with Docker in Node.js, including installing Docker on your machine, creating Docker images and containers, and running your application.

Why use Docker with Node.js?

Before we jump into the technical details of setting up Docker with Node.js, let's take a moment to understand why using Docker can be beneficial for Node.js developers. One of the main advantages of using Docker with Node.js is that it allows for consistent development, testing, and deployment environments. This means that you can develop and test your application in the same environment that it will be deployed to, reducing the risk of compatibility issues and ensuring that your application runs as expected. Additionally, Docker provides a streamlined way to package and deploy your Node.js applications, making it easier to scale and manage your infrastructure. With Docker, you can quickly spin up new instances of your application and easily manage the resources they consume. In the following sections, we'll explore how to set up Docker with Node.js and take advantage of these benefits.

Prerequisites

Before we begin, you should have a basic understanding of Node.js and its package manager, npm. If you don't have Node.js installed, you can follow the official installation guide for your operating system:

You should also have Docker installed on your machine. If you haven't installed Docker yet, follow the official installation guide for your operating system:

Once you have Docker installed, verify that it's running by opening a terminal window and running the following command:

docker --version
Enter fullscreen mode Exit fullscreen mode

This should output the version of Docker that you have installed. If you encounter any issues during installation or verification, you can refer to the Docker documentation for troubleshooting tips.

Note: This tutorial assumes that you have a basic understanding of Node.js and have a text editor installed on your machine. If you're new to Node.js, please refer to the official Node.js documentation. Also, if you need help with installing a text editor like Visual Studio Code, check out the official documentation

Setting up Docker in a Nodejs application

  1. Create a Node.js Application

To set up Docker in Node.js, you need to create a Node.js application. Start by creating a new directory for your application, you can call it node-with-docker. Open your terminal and enter the following command to create the directory:

mkdir node-with-docker
Enter fullscreen mode Exit fullscreen mode

Next, navigate to the newly created directory using the following command:

cd node-with-docker
Enter fullscreen mode Exit fullscreen mode

Once you're in the node-with-docker directory, run the following command to create a new Node.js project using the Node Package Manager (NPM):

npm init
Enter fullscreen mode Exit fullscreen mode

This command will prompt you to answer a few questions about your project, such as the name, version, and description. You can leave the defaults for now, or change them to suit your needs.

After creating your Node.js project, create a new file called index.js in the root directory of your project. This file will contain the application code. Here is an example of a simple Node.js application that sets up a basic HTTP server that listens on port 8000 and returns a "Hello World" response to any incoming requests.

const http = require('http');

const hostname = '0.0.0.0';
const port = 8000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World\n');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});
Enter fullscreen mode Exit fullscreen mode

Save the above code to index.js in the node-with-docker directory.

With your Node.js application set up, you can move on to creating a Dockerfile to containerize it.

  1. Create a Dockerfile

Once you have a basic Node.js application set up, the next step is to create a Dockerfile. A Dockerfile is a script that contains instructions for building a Docker image. In this case, we'll create a Dockerfile that builds an image for your application.

Create a new file named Dockerfile (no extension) in the same directory as your index.js file. Inside this file, add the following code:

# Use an official Node.js runtime as a parent image
FROM node:16-alpine

# Set the working directory to /app
WORKDIR /app

# Copy the current directory contents into the container at /app
COPY . /app

# Install any needed packages specified in package.json
RUN npm install

# Make port 8000 available to the world outside this container
EXPOSE 8000

# Run index.js when the container launches
CMD ["node", "index.js"]
Enter fullscreen mode Exit fullscreen mode

This Dockerfile starts by using an official Node.js runtime as the parent image. It sets the working directory to /app, copies the current directory into the container at /app, and installs any needed packages using npm install. It then exposes port 8000 to the world outside the container and runs the index.js file when the container launches.

  1. Build the Docker image

With your Dockerfile in place, you can use it to build a Docker image for your Node.js application.

Open your terminal and navigate to the directory where your index.js and Dockerfile files are located. Run the following command to build the Docker image:

docker build -t nodewithdocker .
Enter fullscreen mode Exit fullscreen mode

This command tells Docker to build a new image with the tag nodewithdocker, using the Dockerfile in the current directory (represented by the .).

  1. Run the Docker Container

With your Docker image built, you can now run a Docker container for your Node.js application.

Run the following command to start a Docker container for your Node.js application:

docker run -p 8000:8000 nodewithdocker
Enter fullscreen mode Exit fullscreen mode

This command starts a new Docker container for your nodewithdocker image and maps port 8000 from the container to port 8000 on your host machine.

  1. Test the Node.js Application in the Docker Container

With the Docker container running, you can now test your Node.js application by visiting http://0.0.0.0:8000 in your web browser. You should see a "Hello World" response, indicating that your application is running inside the Docker container.

Congratulations! You have successfully set up Docker in a Node.js application. With Docker, you can now easily package your Node.js application and its dependencies into a container, making it easy to deploy your application to any machine with Docker installed.

Conclusion

In addition to simplifying your development workflow, Docker also offers numerous benefits such as scalability, portability, and security. Docker allows you to quickly scale your application by spinning up new containers and distributing the load, making it ideal for applications with varying traffic demands. It also makes it easy to deploy your application to different environments without worrying about compatibility issues. And with Docker's built-in security features, you can ensure that your application is protected from potential threats.

Overall, Docker is an essential tool for any Node.js developer looking to streamline their development workflow, improve application performance, and simplify the deployment process. With the knowledge gained in this article, you can start leveraging the power of Docker in your own Node.js applications and take your development process to the next level.

Top comments (1)

Collapse
 
mooha1999 profile image
mooha1999

Great article. I suggest you use different port numbers in the running command to be able to distinguish between the container port and the host port