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
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"}}
Run:
npminstall
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}`);});
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:
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"]
Step 6: Build and Run the Containers
- Build the services:
docker-compose build
- Start the containers:
docker-compose up
- Verify the containers:
docker ps
Step 7: Test the Application
- Access the Node.js application at
http://localhost:3000/
. 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
- Stop the containers:
docker-compose down
- Restart the containers:
docker-compose up
- 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
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)
For further actions, you may consider blocking this person and/orreporting abuse