In this post, we will walk through the process of setting up a simple Node.js application, connecting it to a MongoDB database using Docker containers, and utilizing Mongo Express for an easy-to-use database interface. This tutorial is designed for beginners who want to learn how to integrate these technologies for a smooth development experience.
What You Will Learn:
- Setting up a Node.js application
- Creating a Docker environment for Node.js and MongoDB
- Using Mongo Express to manage your MongoDB database
Prerequisites
Before we begin, make sure you have the following installed on your machine:
Step 1: Set Up Your Node.js Application
First, let's create a simple Node.js application.
a. Create a Project Directory
Open your terminal and run the following commands to create a new directory for your project and navigate into it:
mkdir node-docker-demo
cd node-docker-demo
b. Initialize a New Node.js Project
Run the following command to create a new package.json
file with default settings:
npm init -y
c. Install Necessary Packages
Install Express for the web server and Mongoose for interacting with MongoDB:
npm install express mongoose
d. Create a Simple index.js
File
Create a new file named index.js
in your project directory and add the following code:
const express = require('express');
const mongoose = require('mongoose');
const app = express();
const port = 3000;
// Middleware to parse JSON bodies
app.use(express.json());
// Connect to MongoDB
mongoose.connect('mongodb://mongo:27017/mydatabase', { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('Connected to MongoDB'))
.catch(err => console.error('Could not connect to MongoDB...', err));
// Define a simple schema and model
const ItemSchema = new mongoose.Schema({
name: String
});
const Item = mongoose.model('Item', ItemSchema);
// API endpoint to get all items
app.get('/items', async (req, res) => {
const items = await Item.find();
res.send(items);
});
// API endpoint to create a new item
app.post('/items', async (req, res) => {
const newItem = new Item(req.body);
await newItem.save();
res.send(newItem);
});
app.listen(port, () => {
console.log(`App listening at http://localhost:${port}`);
});
Step 2: Set Up Docker Environment
Next, we'll set up Docker to containerize our Node.js application and MongoDB.
a. Create a Dockerfile
for the Node.js Application
In your project directory, create a file named Dockerfile
and add the following content:
# Use the official Node.js image as the base image
FROM node:14
# Create and change to the app 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 code
COPY . .
# Expose the port the app runs on
EXPOSE 3000
# Run the application
CMD ["node", "index.js"]
b. Create a docker-compose.yml
File
In your project directory, create a file named docker-compose.yml
and add the following content:
version: '3.8'
services:
app:
build: .
ports:
- "3000:3000"
depends_on:
- mongo
environment:
- MONGO_URI=mongodb://mongo:27017/mydatabase
mongo:
image: mongo:latest
ports:
- "27017:27017"
volumes:
- mongo-data:/data/db
mongo-express:
image: mongo-express:latest
ports:
- "8081:8081"
environment:
- ME_CONFIG_MONGODB_SERVER=mongo
- ME_CONFIG_MONGODB_ADMINUSERNAME=admin
- ME_CONFIG_MONGODB_ADMINPASSWORD=pass
volumes:
mongo-data:
Step 3: Start the Application
Now that we have our Docker setup ready, let's build and run our containers.
a. Build and Run the Docker Containers
Run the following command in your terminal to build and start your Docker containers:
docker-compose up --build
Docker will download the necessary images, build your application container, and start everything up. You should see logs indicating that your Node.js application is running and connected to MongoDB.
Step 4: Access the Application and Mongo Express
- Open your browser and go to
http://localhost:3000/items
to access the Node.js application. - Open your browser and go to
http://localhost:8081
to access Mongo Express.
Conclusion
Congratulations! You have successfully set up a simple Node.js application connected to a MongoDB database using Docker containers. Additionally, you now have a user-friendly interface to manage your MongoDB database with Mongo Express. This setup provides a solid foundation for developing more complex applications with these technologies. Happy coding!
Top comments (0)