DEV Community

Vivesh
Vivesh

Posted on

3

Devops Open source project Task

To persist data for a MongoDB container by attaching a Docker volume and demonstrate the use of Docker volumes with a Node.js and MongoDB project, here’s a step-by-step approach.


Step 1: Install Docker

Ensure Docker is installed and running on your system. If not, install it following the official Docker installation guide.


Step 2: Create the Project Structure

Set up a directory structure for the project:

persist-docker-volumes/
├── backend/
│   ├── app.js
│   ├── package.json
│   ├── package-lock.json
├── docker-compose.yml
├── Dockerfile
Enter fullscreen mode Exit fullscreen mode

Step 3: Write the Node.js Application

Create a basic Node.js application to interact with MongoDB.

backend/package.json:

{
  "name": "docker-volume-demo",
  "version": "1.0.0",
  "main": "app.js",
  "dependencies": {
    "express": "^4.17.3",
    "mongoose": "^6.0.0"
  },
  "scripts": {
    "start": "node app.js"
  }
}
Enter fullscreen mode Exit fullscreen mode

Run:

npm install
Enter fullscreen mode Exit fullscreen mode

backend/app.js:

const express = require("express");
const mongoose = require("mongoose");

const app = express();
app.use(express.json());

// MongoDB connection
mongoose.connect("mongodb://mongo:27017/dockerVolumeDemo", {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

const db = mongoose.connection;
db.on("error", console.error.bind(console, "MongoDB connection error:"));
db.once("open", () => {
  console.log("Connected to MongoDB!");
});

// Define a simple schema and model
const UserSchema = new mongoose.Schema({
  name: String,
});
const User = mongoose.model("User", UserSchema);

// Routes
app.get("/", (req, res) => {
  res.send("Welcome to the Docker Volumes Demo!");
});

app.post("/users", async (req, res) => {
  const user = new User(req.body);
  await user.save();
  res.json(user);
});

app.get("/users", async (req, res) => {
  const users = await User.find();
  res.json(users);
});

const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});
Enter fullscreen mode Exit fullscreen mode

Step 4: Create the Docker Compose File

docker-compose.yml:

version: "3.9"

services:
  backend:
    build: .
    ports:
      - "3000:3000"
    depends_on:
      - mongo
    volumes:
      - ./backend:/app
    environment:
      - NODE_ENV=development

  mongo:
    image: mongo:latest
    ports:
      - "27017:27017"
    volumes:
      - mongodb_data:/data/db

volumes:
  mongodb_data:
Enter fullscreen mode Exit fullscreen mode

Step 5: Write the Dockerfile

Dockerfile:

# Use Node.js image
FROM node:14

# Set working directory
WORKDIR /app

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

# Install dependencies
RUN npm install

# Copy application files
COPY backend/ .

# Expose port
EXPOSE 3000

# Start the app
CMD ["npm", "start"]
Enter fullscreen mode Exit fullscreen mode

Step 6: Build and Run the Containers

  1. Build the services:
   docker-compose build
Enter fullscreen mode Exit fullscreen mode
  1. Start the containers:
   docker-compose up
Enter fullscreen mode Exit fullscreen mode
  1. Verify the containers:
   docker ps
Enter fullscreen mode Exit fullscreen mode

Step 7: Test the Application

  1. Access the Node.js application at http://localhost:3000/.
  2. Use an API tool like Postman or curl to test endpoints:

    • Create a user:
     curl -X POST -H "Content-Type: application/json" -d '{"name": "John"}' http://localhost:3000/users
    
  • Retrieve users:

     curl http://localhost:3000/users
    

Step 8: Verify Data Persistence

  1. Stop the containers:
   docker-compose down
Enter fullscreen mode Exit fullscreen mode
  1. Restart the containers:
   docker-compose up
Enter fullscreen mode Exit fullscreen mode
  1. Access the /users endpoint again. The previously created data should still be present, as it’s stored in the Docker volume.

Step 9: Clean Up

To remove the containers and associated volume:

docker-compose down --volumes
Enter fullscreen mode Exit fullscreen mode

Technologies Used

  • Docker: For containerizing the application and MongoDB.
  • Node.js: For the backend server interacting with MongoDB.
  • MongoDB: As the database.
  • Docker Volumes: To persist MongoDB data across container restarts.

This project demonstrates how to use Docker volumes to ensure data persistence in a containerized environment while integrating Node.js and MongoDB.

Happy Learning!!!

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay