How to use docker in your node and react applications with mongodb

How to use docker in your node and react applications with mongodb

Hiral Shah

24 Oct 2023

7 MINUTES READ

Introduction

Docker has revolutionized the way developers build, ship, and run applications. Its flexibility and portability have made it an essential tool in modern software development. This article will guide you through the process of using Docker in your Node and React applications while integrating a MongoDB database. By the end, you'll be well-equipped to create, deploy, and manage your applications with ease.

What is docker?

In simple terms, Docker is a platform for developing, shipping, and running applications. It allows developers to package an application and its dependencies into a single unit called a container. Containers are lightweight, efficient, and easily portable across different environments. This makes it an ideal choice for building and deploying Node and React applications.

Benefits of using docker for application development

  • Isolation: Containers encapsulate applications and their dependencies, ensuring a consistent and isolated environment for development and deployment.
  • Portability: Containers can run consistently across different platforms and environments, making it easier to collaborate with others and deploy applications seamlessly.
  • Efficiency: Docker optimizes resource usage, making it a cost-effective solution for hosting applications.

Setting up your environment

Before diving into Dockerizing your Node and React applications, you need to set up your development environment.

Prepare Your Development Environment: Ensure Node.js and npm are installed on your system. Create a directory for your project.

|- my-dockerized app

|- Backend

|- Dockerfile

|- Frontend

|- Dockerfile

|- Docker-compose.yml

|- Dockerfile

Install Docker: Visit the Docker website www.docker.com to download and install Docker for your operating system. With your environment ready, you can now proceed with Dockerizing your applications.

Creating a dockerized node application

Dockerizing a Node application involves creating a Docker container that encapsulates your Node.js application and its dependencies. Follow these steps to get started:

Dockerfile: Create a Dockerfile in your project directory. This file defines the configuration for your Docker container, including the base image, application setup, and runtime environment.


    FROM node:14
    # Install MongoDB client tools
    RUN apt-get update && apt-get install -y mongo-tools

    # Set the working directory
    WORKDIR /app

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

    # Install dependencies
    RUN npm install --only=production

    # Copy the rest of the application files
    COPY . .

    # Start the application
    CMD ["npm", "start"]
        

Building the docker image: Use the docker build command to build your Docker image based on the Dockerfile.


    DevOps@techvoot:~/project/my-dockerized-app/backend$ docker build -t my-dockerized-app_backend .
    [+] Building 4.4s (12/12) FINISHED                                                                                              docker:default
    => [internal] load build definition from Dockerfile                                                                                      0.0s
        => => transferring dockerfile: 403B                                                                                                      0.0s
        => [internal] load .dockerignore                                                                                                         0.0s
        => => transferring context: 2B                                                                                                           0.0s
        => [internal] load metadata for docker.io/library/node:14                                                                                3.6s
        => [auth] library/node:pull token for registry-1.docker.io                                                                               0.0s
        => [internal] load build context                                                                                                         0.7s
        => => transferring context: 1.31MB                                                                                                       0.6s
        => [1/6] FROM docker.io/library/node:14@sha256:a158d3b9b4e3fa813fa6c8c590b8f0a860e015ad4e59bbce5744d2f6fd8461aa                          0.0s
        => CACHED [2/6] RUN apt-get update && apt-get install -y mongo-tools                                                                     0.0s
        => CACHED [3/6] WORKDIR /backend                                                                                                         0.0s
        => CACHED [4/6] COPY package*.json ./                                                                                                    0.0s
        => CACHED [5/6] RUN npm install --only=production                                                                                        0.0s
        => CACHED [6/6] COPY . .                                                                                                                 0.0s
        => exporting to image                                                                                                                    0.0s
        => => exporting layers                                                                                                                   0.0s
        => => writing image sha256:0be25283af4464386b8f2724073c634f3d21eae3c95a7d3c693e3820964b9176                                              0.0s
        => => naming to docker.io/library/my-dockerized-app_backend
            

Running the container: Once the image is built, you can use the docker run command to start a container based on your Node application image.


    DevOps@techvoot:~/project/my-dockerized-app/backend$ docker images
    REPOSITORY                 TAG      IMAGE ID      CREATED      SIZE
    my-dockerized-app_backend  latest   0be25283af44  10 days ago  1.75GB
    DevOps@techvoot:~/project/my-dockerized-app/backend$ docker run -d -p 4002:4001 --name node-container my-dockerized-app_backend
    99b03d3fd01c88c3606ad3c7eb029d64511d03bbf500406eccee2acd3b6b1d8d
    DevOps@techvoot:~/project/my-dockerized-app/backend$ docker ps
    CONTAINER ID  IMAGE                      COMMAND                 CREATED        STATUS        PORTS                                      NAMES
    99b03d3fd01c  my-dockerized-app_backend  "docker-entrypoint.s…"  6 seconds ago  Up 5 seconds  0.0.0.0:4002->4001/tcp, :::4002->4001/tcp  node-container
        

Dockerizing react applications

React applications can also benefit from Docker. Containerizing a React app involves a slightly different approach, as React primarily runs in the user's web browser.

Dockerfile: Similar to Node applications, create a Dockerfile for your React app. This file should include the necessary build instructions.


    FROM node:14-alpine

    WORKDIR /frontend

    COPY package*.json ./

    RUN npm install

    COPY . .

    RUN npm run build

    CMD ["npm", "start"]
    

Optimizing the build: Use multi-stage builds to create a minimal, efficient image for your React application.


    DevOps@techvoot:~/project/my-dockerized-app/frontend$ docker build -t my-dockerized-app_frontend .
    [+] Building 4.3s (11/11) FINISHED                                                                                              docker:default
    => [internal] load .dockerignore                                                                                                         0.0s
    => => transferring context: 2B                                                                                                           0.0s
    => [internal] load build definition from Dockerfile                                                                                      0.0s
    => => transferring dockerfile: 169B                                                                                                      0.0s
    => [internal] load metadata for docker.io/library/node:14-alpine                                                                         2.4s
    => [1/6] FROM docker.io/library/node:14-alpine@sha256:434215b487a329c9e867202ff89e704d3a75e554822e07f3e0c0f9e606121b33                   0.0s
    => [internal] load build context                                                                                                         1.8s
    => => transferring context: 5.58MB                                                                                                       1.8s
    => CACHED [2/6] WORKDIR /frontend                                                                                                        0.0s
    => CACHED [3/6] COPY package*.json ./                                                                                                    0.0s
    => CACHED [4/6] RUN npm install                                                                                                          0.0s
    => CACHED [5/6] COPY . .                                                                                                                 0.0s
    => CACHED [6/6] RUN npm run build                                                                                                        0.0s
    => exporting to image                                                                                                                    0.0s
    => => exporting layers                                                                                                                   0.0s
    => => writing image sha256:313a73feeb1db35afd52e351f5cea6ba44e823c6cc241d815f209fcb45f1abdd                                              0.0s
    => => naming to docker.io/library/my-dockerized-app_frontend
    

Handling dependencies: Ensure all dependencies are resolved within the Docker container.


    DevOps@techvoot:~/project/my-dockerized-app/frontend$ docker images
    REPOSITORY                   TAG       IMAGE ID       CREATED       SIZE
    my-dockerized-app_frontend   latest    313a73feeb1d   10 days ago   1.31GB
    my-dockerized-app_backend    latest    0be25283af44   10 days ago   1.75GB
    DevOps@techvoot:~/project/my-dockerized-app/frontend$  docker run -d -p 3001:3000 --name react-container my-dockerized-app_frontend
    bd6791dee45fce52d1e0cdf1bea072d69984163aba75733ed354c8c6b7f196b2
    DevOps@techvoot:~/project/my-dockerized-app/frontend$ docker ps
    CONTAINER ID   IMAGE                        COMMAND                  CREATED         STATUS         PORTS                                       NAMES
    bd6791dee45f   my-dockerized-app_frontend   "docker-entrypoint.s…"   6 seconds ago   Up 5 seconds   0.0.0.0:3001->3000/tcp, :::3001->3000/tcp   react-container
    9981f9c53170   my-dockerized-app_backend    "docker-entrypoint.s…"   3 minutes ago   Up 3 minutes   0.0.0.0:4002->4001/tcp, :::4002->4001/tcp   node-container
    

Connecting to MongoDB

MongoDB is a popular choice for database management, especially in Node.js applications. To connect your Node and React applications to a MongoDB database within Docker containers, follow these steps:

Dockerfile: To create a Dockerfile for MongoDB in the project's root, you can use an official MongoDB Docker image as the base image and add any additional configuration or data initialization that your application requires. Here's a basic Dockerfile for running a MongoDB container:


    FROM mongo
    WORKDIR /my-dockerized-app
    COPY . .
    CMD ["mongod"]            
    

Docker compose: Create a docker-compose.yml file to define the services and their configurations. Include MongoDB and your Node application as separate services.


    version: '3'
    services:
        frontend:
        build:
            context: ./frontend
            dockerfile: Dockerfile
        ports:
            - 3000:3000
        volumes:
            - frontend-volume:/frontend/public
        backend:
        build:
            context: ./backend
            dockerfile: Dockerfile
        ports:
            - 4002:4001
        volumes:
            - backend-volume:/backend/uploads
        depends_on:
            - database
        database:
        build:
            context: .
            dockerfile: Dockerfile
        image: mongo
        volumes:
            - database-volume:/data/db


    volumes:
        frontend-volume:
        backend-volume:
        database-volume:                      
    

Building and running containers

Now that you've created Docker containers for your applications, it's time to build and run them. Here are some essential commands to know:

  • Docker build: Build Docker images
  • Docker run: Start containers based on images
  • Docker ps: List running containers.
  • Docker stop: Stop a running container.

    DevOps@techvoot:~/project/my-dockerized-app$ docker-compose up -d
    Creating network "my-dockerized-app_default" with the default driver
    Creating my-dockerized-app_database_1 ... done
    Creating my-dockerized-app_frontend_1 ... done
    Creating my-dockerized-app_backend_1  ... done
    DevOps@techvoot:~/project/my-dockerized-app$ docker ps
    CONTAINER ID   IMAGE                        COMMAND                  CREATED          STATUS          PORTS                                       NAMES
    3cd498790d8a   my-dockerized-app_backend    "docker-entrypoint.s…"   25 seconds ago   Up 24 seconds   0.0.0.0:4002->4001/tcp, :::4002->4001/tcp   my-dockerized-app_backend_1
    62198d6e48bc   mongo                        "docker-entrypoint.s…"   25 seconds ago   Up 24 seconds   27017/tcp                                   my-dockerized-app_database_1
    f02930f446c1   my-dockerized-app_frontend   "docker-entrypoint.s…"   25 seconds ago   Up 24 seconds   0.0.0.0:3000->3000/tcp, :::3000->3000/tcp   my-dockerized-app_frontend_1
    

Deploying your applications

Once your Dockerized applications are ready, you can deploy them to a hosting environment. Consider services like AWS, Azure, or Docker Swarm for production deployment. Ensure that you follow best practices for securing your containers and managing your deployment.

Tips for effective applications docker usage

Here are some tips to make the most out of Docker in your Node and React applications:

  • Use Docker Compose for managing multi-container applications.
  • Implement continuous integration and continuous deployment (CI/CD) pipelines for automated testing and deployment.
  • Regularly update your Docker images and containers to include security patches and updates.

Conclusion

In corporating Docker into your Node and React application development can streamline your workflow, enhance collaboration, and simplify deployment. Docker's portability and efficiency make it a valuable addition to your development toolbox.

Get started with Docker today, and experience the benefits firsthand. Your Node and React applications, along with MongoDB, will thrive in this containerized environment.


Hiral Shah
Hiral Shah

DevOps Engineer at Techvoot solutions

Hiral Shah is a proficient DevOps engineer, specializing in automation and cloud technologies. Her skills enhance collaboration and efficiency within development and operations teams, ensuring project success.

Linkedin
Hire Skilled Developer

*Please fill all the required fields

Get our Newsletter

Customized solutions for your projects

*Please fill all the required fields