DEV Community

Zeshan
Zeshan

Posted on

How to Dockerize a Node.js Application

Docker makes it easy to run applications in the same environment, whether you're on Windows, Linux, or macOS. In this guide, we'll show you how to "dockerize" a Node.js application.

Image description

This means packaging your app and its dependencies into a container, so it runs smoothly anywhere.

What You'll Need

Make sure you have these installed on your computer:

Step 1: Set Up Your Node.js Application

First, let's create a simple Node.js app using Express.

  1. Create a new project folder:

    mkdir my-node-app
    cd my-node-app
    
  2. Initialize a new Node.js project:

    npm init -y
    
  3. Install Express:

    npm install express
    
  4. Create an index.js file and add this code:

    const express = require('express');
    const app = express();
    const port = 3000;
    
    app.get('/', (req, res) => {
        res.send('Hello, Docker!');
    });
    
    app.listen(port, () => {
        console.log(`App listening at http://localhost:${port}`);
    });
    
  5. Test your app:

    node index.js
    

    Open your browser and go to http://localhost:3000. You should see "Hello, Docker!".

Step 2: Create a Dockerfile

A Dockerfile tells Docker how to build your application. Create a file named Dockerfile in your project folder and add the following:

# Use an official Node.js image as the base
FROM node:14

# Set the working directory
WORKDIR /usr/src/app

# Copy package.json and package-lock.json
COPY package*.json ./

# Install dependencies
RUN npm install

# Copy the rest of the application
COPY . .

# Expose the port your app runs on
EXPOSE 3000

# Command to run the app
CMD ["node", "index.js"]
Enter fullscreen mode Exit fullscreen mode

Step 3: Build Your Docker Image

Open your terminal, make sure you're in the project folder, and run:

docker build -t my-node-app .
Enter fullscreen mode Exit fullscreen mode

This command tells Docker to build an image named my-node-app using the instructions in the Dockerfile.

Step 4: Run Your Docker Container

Now, let's run our container:

docker run -p 3000:3000 my-node-app
Enter fullscreen mode Exit fullscreen mode

This command tells Docker to run the my-node-app image and map port 3000 on your machine to port 3000 in the container.

Step 5: Access Your Application

Open your browser and go to http://localhost:3000. You should see "Hello, Docker!" again, but this time it's running inside a Docker container.

Conclusion

You’ve successfully dockerized your Node.js application! Now you can be sure it will run the same way on any machine with Docker installed. This makes it easier to share and deploy your app.

Dockerizing applications can seem complex at first, but with practice, it becomes a powerful tool in your development workflow. Happy coding!

Top comments (0)