Site icon CentLinux

How to run a Nodejs Docker Container

Share on Social Media

Learn how to run a Nodejs Docker container with our step-by-step guide. Discover how to create a Dockerfile, build an image, and deploy your Nodejs application efficiently. Perfect for developers aiming to streamline their development and deployment process. #centlinux #linux #docker

What is Nodejs?

Nodejs is an open-source, cross-platform JavaScript runtime environment that allows developers to execute JavaScript code outside of a web browser. Built on Chrome’s V8 JavaScript engine, Nodejs is designed for building scalable network applications, particularly web servers and real-time applications like chat programs.

Key Features

  1. Asynchronous and Event-Driven: Nodejs uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. This is particularly useful for handling multiple simultaneous connections, making it ideal for real-time applications.
  2. Single-Threaded: Despite being single-threaded, Node.js can handle many concurrent connections with high throughput, thanks to its non-blocking architecture.
  3. NPM (Node Package Manager): Node.js comes with NPM, a powerful package manager that provides access to thousands of reusable modules, libraries, and tools that can be easily integrated into applications.
  4. Cross-Platform: Node.js runs on various platforms, including Windows, Linux, Unix, and macOS, making it highly versatile for different development environments.
  5. Rich Ecosystem: The vast ecosystem of Node.js includes frameworks like Express.js, Koa.js, and Nest.js, which simplify the development of web applications and APIs.

Common Use Cases

How to run Node.js Docker Container

Advantages of Using Nodejs

Nodejs is a popular choice for modern web development, offering efficiency and scalability for a wide range of applications.

Recommended Training: Docker for the Absolute Beginner – Hands On – DevOps from Mumshad Mannambeth

Docker Host Specification

In this setup, we are utilizing a preconfigured Docker host that has been prepared with the necessary software and configurations to run Docker containers efficiently. The server is equipped with the following specifications, ensuring optimal performance and compatibility for running Nodejs applications within a containerized environment.

If you want to see how to configure a Docker Host, the you can follow our following articles.

Create a Directory for Nodejs Docker Project

Connect to the Docker host server (docker-01.centlinux.com) as an administrative user using an SSH client or terminal. Ensure you have the necessary permissions to manage Docker containers.

Once connected, create a dedicated directory for your Nodejs Docker project. This directory will store all essential files, including the application code, Dockerfile, and configuration files needed to build and run the container.

ahmer@docker-01:~$ mkdir ~/nodejs_docker
ahmer@docker-01:~$ cd nodejs_docker

Develop Node Web App

To maintain simplicity and focus on the containerization process, we are creating a basic “Hello, World!” Node.js web application. This minimalistic application will serve as a starting point for running a Node.js project inside a Docker container.

It will include a simple web server that responds with “Hello, World!” when accessed via a web browser or API request. This approach allows us to demonstrate the fundamental steps of building, containerizing, and running a Node.js application using Docker.

ahmer@docker-01:~/nodejs_docker$ nano myapp.js

And add following lines of code to create a simple “Hello World” application.

'use strict';

const express = require('express');

// Constants
const PORT = 3000;
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 at http://${HOST}:${PORT}`);

Create the Nodejs package.json file. This file provides the meta data information for our Nodejs Docker application.

{
"name": "myapp",
"version": "1.0.0",
"description": "Node.js on Docker",
"author": "Alaric Bird <alaric.bird@gmail.com>",
"main": "myapp.js",
"scripts": {
"start": "node myapp.js"
},
"dependencies": {
"express": "^4.16.1"
}
}

Create a Docker file for Nodejs Docker Project:

To define the deployment procedure such as docker image to be used, dependencies, service port, etc. We are required to create a Dockerfile for our Nodejs Docker container.

ahmer@docker-01:~/nodejs_docker$ nano Dockerfile

Add following directives therein (each directive is briefly described in the comments before it).

# Docker Image to be used
FROM node:13-alpine

# Create a working directory within NodeJS Docker container
WORKDIR /usr/src/app

# Install app dependencies
# A wildcard is used to ensure both package.json AND package-lock.json are copied where available (npm@5+)
COPY package*.json ./

RUN npm install

# Bundle the App source
COPY . .

# Expose the port 3000 to network computers
EXPOSE 3000

#Run the node command and start our web application
CMD [ "node", "myapp.js" ]

We are using the node:13-alpine image here, because it is the lightest image that will fulfill our project’s requirement.

However, there are many variants of the node images are available at the Docker Hub. To get the complete list, you can visit the Official Docker Images for Nodejs Page.

Build the Nodejs Docker Image

We have successfully created both the Dockerfile and the Node.js web application, ensuring that all necessary configurations and dependencies are in place for containerization.

The next step is to build a Docker image for our Node.js web application using the Dockerfile. This process packages the application along with its required runtime environment, making it portable and easy to deploy across different systems. Once the image is built, it can be used to create and run containers that host the application efficiently.

ahmer@docker-01:~/nodejs_docker$ sudo docker build .
Sending build context to Docker daemon  4.096kB
Step 1/7 : FROM node:13-alpine
 ---> 483343d6c5f5
Step 2/7 : WORKDIR /usr/src/app
 ---> Using cache
 ---> bad78ca928c6
Step 3/7 : COPY package*.json ./
 ---> Using cache
 ---> fdd7ac2c1274
Step 4/7 : RUN npm install
 ---> Using cache
 ---> 8a34ec80bd87
Step 5/7 : COPY . .
 ---> 873f9ddd4360
Step 6/7 : EXPOSE 3000
 ---> Running in 7d567e0f4da3
Removing intermediate container 7d567e0f4da3
 ---> b3e087682594
Step 7/7 : CMD [ "node", "myapp.js" ]
 ---> Running in 4e170d3a1567
Removing intermediate container 4e170d3a1567
 ---> 7be386175292
Successfully built 7be386175292

In this setup, we have built the Docker image locally on our Docker host. However, if you want to make the image accessible from multiple systems or share it with others, you can build and push it to Docker Hub.

To do this, you will need a Docker Hub account and must authenticate using your Docker Hub credentials. Once uploaded, the image can be pulled and deployed on any system with Docker installed, ensuring easy distribution and scalability.

Run Nodejs Docker Container

Start a container by using above Docker image.

ahmer@docker-01:~/nodejs_docker$ sudo docker run 
> --name nodejs-docker-app 
> -p 80:3000 
> -d 
> 7be386175292
87f61f85cd0546786a2af8a5eb6da1402e753a1239a0f1088a735217130a603b

We have started our Nodejs Docker container. Check its log now.

ahmer@docker-01:~/nodejs_docker$ sudo docker logs nodejs-docker-app
Running at http://0.0.0.0:3000

Read Also: How to install Nodejs Server on CentOS 8

Test the Dockerized Nodejs Application

To verify that the Node.js application is running inside the Docker container, you can access it using the curl command from the terminal. This allows you to send an HTTP request to the application and check its response.

Ensure that the container is running and listening on the correct port. If necessary, use the server’s IP address or hostname along with the exposed port to make the request.

ahmer@docker-01:~/nodejs_docker$ curl localhost:80
Hello World!

Our Nodejs application has been deployed in a Docker container.

Final Thoughts

Running a Nodejs application within a Docker container can significantly enhance your development and deployment process. By containerizing your application, you ensure consistency across different environments, ease scalability, and simplify dependency management. Docker provides a robust platform for deploying Node.js applications seamlessly, whether for development, testing, or production.

If you need expert assistance in running your Nodejs Docker container or any other Docker-related services, I’m here to help. With my extensive experience in Docker and Nodejs, I can provide tailored solutions to meet your specific needs.

Searching for a skilled Linux admin? From server management to security, I ensure seamless operations for your Linux systems. Find out more on my Fiverr profile!

Feel free to reach out, and let’s take your project to the next level!

FAQs

What do I need to run a Nodejs container?
You need Docker installed on your system and a Nodejs application with a Dockerfile.

How do I create a Docker image for my Nodejs app?
Build the image using Docker commands by specifying the necessary configurations in a Dockerfile.

How can I run a Nodejs container?
Use Docker to run the container, ensuring necessary ports are mapped for external access.

How do I manage environment variables in a Nodejs container?
Pass them using the Docker CLI or define them in an environment file (.env).

How can I keep my Nodejs container running?
Run it in detached mode (-d) or use process managers like PM2 inside the container.

Exit mobile version