How to create a docker container for a node.js application

Introduction

A Docker container is a lightweight, standalone, executable package of software that includes everything needed to run an application, including the code, runtime, system tools, libraries, and settings. Containers are similar to virtual machines in that they provide an isolated environment for running applications, but they are much more lightweight and efficient because they share the host operating system kernel.

Each container runs as an isolated process in its own namespace, which means that it has its own file system, network stack, and process table. This isolation ensures that the containerized application runs consistently across different environments, regardless of the host system’s configuration.

Docker containers are created from Docker images, which are essentially a snapshot of the application’s code and dependencies at a specific point in time. Containers can be easily deployed and managed using Docker, which provides a set of tools and APIs for building, sharing, and running containers.

To create a Docker container for a Node.js application, you can follow these steps:

  1. Create a Dockerfile: In the root directory of your Node.js application, create a file called Dockerfile with the following content:
FROM node:14

WORKDIR /app

COPY package*.json ./

RUN npm install

COPY . .

EXPOSE 3000

CMD [ "npm", "start" ]

This Dockerfile specifies that we want to use the official Node.js 14 image as the base image, sets the working directory to /app, copies the package.json and package-lock.json files into the container and runs npm install to install the dependencies, copies the entire application into the container, exposes port 3000, and finally runs the command npm start to start the Node.js application.

  1. Build the Docker image: To build the Docker image, run the following command in the terminal in the same directory as the Dockerfile:
docker build -t my-node-app .

This command tells Docker to build an image from the Dockerfile in the current directory and tag it with the name my-node-app.

  1. Run the Docker container: To run the Docker container, use the following command:
docker run -p 3000:3000 my-node-app

This command tells Docker to start a container from the my-node-app image and map port 3000 from the container to port 3000 on the host.

Your Node.js application should now be running in a Docker container and accessible at http://localhost:3000.

, , , , ,

Related posts

Latest posts

Leave a Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Please disable your adblocker or whitelist this site!

How to whitelist website on AdBlocker?

How to whitelist website on AdBlocker?

  1. 1 Click on the AdBlock Plus icon on the top right corner of your browser
  2. 2 Click on "Enabled on this site" from the AdBlock Plus option
  3. 3 Refresh the page and start browsing the site