DEV Community

lizahakem
lizahakem

Posted on

Step-by-step tutorial on how to dockerize a Node.js API with a MongoDB database

Step 1: Set up the Node.js API

  1. Create a new directory for your Node.js API project.

  2. Initialize a new Node.js project using npm init and follow the prompts to set up the project.

  3. Install the required dependencies for your Node.js API using npm install. This may include libraries such as Express, MongoDB client, etc.

  4. Write your Node.js API code, including the necessary routes, controllers, and MongoDB connection logic. Make sure your API is working correctly by testing it locally.

Step 2: Set up Docker

  1. Install Docker on your machine by following the official Docker installation guide for your specific operating system.

  2. Verify that Docker is installed correctly by running docker --version in your terminal. It should display the Docker version information.

Step 3: Create a Dockerfile

  1. Create a new file in the root directory of your Node.js project called Dockerfile.

  2. Open the Dockerfile and add the following content:

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

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

# Copy package.json and package-lock.json to the working directory
COPY package*.json ./

# Install dependencies
RUN npm install

# Copy the rest of the application code
COPY . .

# Expose the API port
EXPOSE 3000

# Start the Node.js application
CMD [ "npm", "start" ]

Enter fullscreen mode Exit fullscreen mode
  1. Save the Dockerfile.

Step 4: Build the Docker image

  1. Open a terminal and navigate to the root directory of your Node.js project where the Dockerfile is located.

  2. Run the following command to build the Docker image:
    docker build -t node-api .

    The -t flag specifies the name and optionally a tag for the Docker image.

Step 5: Set up a MongoDB container

  1. In your terminal, run the following command to pull the MongoDB image from the Docker Hub:
    docker pull mongo

  2. Create a new directory for the MongoDB data to persist outside the container, e.g., data/db.

  3. Start a new MongoDB container using the following command:
    docker run -d -p 27017:27017 -v /path/to/data/db:/data/db --name mongodb mongo

The -d flag runs the container in the background, the -p flag maps the container port 27017 to the host port 27017, and the -v flag mounts the data directory to the container's /data/db directory.

Step 6: Run the Docker containers

  1. Start the MongoDB container by running: docker start mongodb
  2. Start the Node.js API container by running: docker run -p 3000:3000 --name node-api --link mongodb:mongodb -d node-api

Top comments (0)