Step 1: Set up the Node.js API
Create a new directory for your Node.js API project.
Initialize a new Node.js project using npm init and follow the prompts to set up the project.
Install the required dependencies for your Node.js API using npm install. This may include libraries such as Express, MongoDB client, etc.
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
Install Docker on your machine by following the official Docker installation guide for your specific operating system.
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
Create a new file in the root directory of your Node.js project called Dockerfile.
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" ]
- Save the Dockerfile.
Step 4: Build the Docker image
Open a terminal and navigate to the root directory of your Node.js project where the Dockerfile is located.
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
In your terminal, run the following command to pull the MongoDB image from the Docker Hub:
docker pull mongo
Create a new directory for the MongoDB data to persist outside the container, e.g., data/db.
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
- Start the MongoDB container by running:
docker start mongodb
- 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)