A Beginner’s Complete Guide to Dockerizing a Node.js Express Application

Posted by

Dockerizing a Node.js Express Application: Complete Guide for Beginners

Dockerizing a Node.js Express Application: Complete Guide for Beginners

If you are a beginner in the world of Docker and Node.js, you might be wondering how to dockerize a Node.js Express application. In this article, we will walk you through the complete process of dockerizing a Node.js Express application, from setting up your environment to running your application in a Docker container.

Prerequisites

Before we get started, make sure you have the following installed on your machine:

  • Node.js
  • Docker

Setting Up Your Node.js Express Application

First, create a new directory for your Node.js Express application and navigate into it.

		
			mkdir my-express-app
			cd my-express-app
		
	

Next, initialize a new Node.js project using the following command:

		
			npm init -y
		
	

Then, install Express:

		
			npm install express
		
	

Create an index.js file and add the following code to create a simple Express server:

		
			const express = require('express');
			const app = express();

			app.get('/', (req, res) => {
			  res.send('Hello Docker!');
			});

			app.listen(3000, () => {
			  console.log('Server running on port 3000');
			});
		
	

Creating a Dockerfile

Create a new file called Dockerfile in your project directory and add the following content:

		
			FROM node:12

			WORKDIR /usr/src/app

			COPY package*.json ./
			RUN npm install

			COPY . .

			EXPOSE 3000
			CMD [ "node", "index.js" ]
		
	

Building and Running Your Docker Image

Build your Docker image using the following command:

		
			docker build -t my-express-app .
		
	

Once the build is complete, you can run your Docker container:

		
			docker run -p 3000:3000 my-express-app
		
	

Your Node.js Express application is now running in a Docker container!

Conclusion

Congratulations! You have successfully dockerized your Node.js Express application. In this article, we covered the basics of dockerizing a Node.js Express application for beginners. As you continue to work with Docker and Node.js, you will discover more advanced techniques for optimizing your development and deployment processes.