Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Vivesh
Vivesh

Posted on

     

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 officialDocker 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 modeExit 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 modeExit fullscreen mode

Run:

npminstall
Enter fullscreen modeExit fullscreen mode

backend/app.js:

constexpress=require("express");constmongoose=require("mongoose");constapp=express();app.use(express.json());// MongoDB connectionmongoose.connect("mongodb://mongo:27017/dockerVolumeDemo",{useNewUrlParser:true,useUnifiedTopology:true,});constdb=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 modelconstUserSchema=newmongoose.Schema({name:String,});constUser=mongoose.model("User",UserSchema);// Routesapp.get("/",(req,res)=>{res.send("Welcome to the Docker Volumes Demo!");});app.post("/users",async(req,res)=>{constuser=newUser(req.body);awaituser.save();res.json(user);});app.get("/users",async(req,res)=>{constusers=awaitUser.find();res.json(users);});constPORT=3000;app.listen(PORT,()=>{console.log(`Server is running on port${PORT}`);});
Enter fullscreen modeExit fullscreen mode

Step 4: Create the Docker Compose File

docker-compose.yml:

version:"3.9"services:backend:build:.ports:-"3000:3000"depends_on:-mongovolumes:-./backend:/appenvironment:-NODE_ENV=developmentmongo:image:mongo:latestports:-"27017:27017"volumes:-mongodb_data:/data/dbvolumes:mongodb_data:
Enter fullscreen modeExit fullscreen mode

Step 5: Write the Dockerfile

Dockerfile:

# Use Node.js imageFROM node:14# Set working directoryWORKDIR /app# Copy package.json and package-lock.jsonCOPY backend/package*.json ./# Install dependenciesRUNnpminstall# Copy application filesCOPY backend/ .# Expose portEXPOSE 3000# Start the appCMD ["npm", "start"]
Enter fullscreen modeExit fullscreen mode

Step 6: Build and Run the Containers

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

Step 7: Test the Application

  1. Access the Node.js application athttp://localhost:3000/.
  2. Use an API tool like Postman orcurl 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 modeExit fullscreen mode
  1. Restart the containers:
   docker-compose up
Enter fullscreen modeExit 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 modeExit 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!!!

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

####
  • Education
    ☘️
  • Work
    👨‍💻
  • Joined

More fromVivesh

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp