0

I have started learning docker, I am using node.js app for learning so i pulled mongo and mongo-express from dockerhub and then created mongo.yaml file till this everything working fine, then I started docker-compose -f mongo.yaml up for containers are running and then i started node.js from another terminal now when I open my app on localhost 3000 and when i am adding the input and data is storing in the db on localhost:8081, but when i wrote the Dockerfile and the docker build -t app . then docker run -p 3000:3000 app ,then saying server started on port 3000 but getting error help me out.

my app.js file:

var express=require("express")
var bodyParser=require("body-parser")
var MongoClient=require("mongodb").MongoClient;

const app=express()

app.use(express.static(__dirname+"/public"));

app.use(express.urlencoded({
    extended:true
}));
app.use(express.json())

app.post("/sign_up",(req,res)=>{
    var name=req.body.name;
    var email=req.body.email;
    var subject=req.body.subject;
    var message=req.body.message;
    var data={
                "name":name,
                "email":email,
                "subject":subject,
                "message":message
            }
            MongoClient.connect('mongodb://admin:password@localhost:27017',function(err,client){
                if(err) throw err;
                var db=client.db("Enquiry-Form");
                db.collection('users').insertOne(data,(err,collection)=>{
                    if(err){
                        throw err;
                    }
            });
        console.log("Data Has been Recorded in Database Successfully");
    });
    return res.redirect('/index.html')
})
app.use("/", (req, res) => {
    res.sendFile(__dirname + "/index.html");
  });
  var port = 3000;

app.listen(port, () => {
    console.log("Server listening on port " + port);
});

mongo.yaml file:

version: '3'
services:
  mongodb:
    image: mongo
    restart: always
    ports:
      - "27017:27017"
    environment:
      MONGO_INITDB_ROOT_USERNAME: admin
      MONGO_INITDB_ROOT_PASSWORD: password

  mongo-express:
    image: mongo-express
    restart: always
    ports:
      - "8081:8081"
    environment:
      ME_CONFIG_MONGODB_ADMINUSERNAME: admin
      ME_CONFIG_MONGODB_ADMINPASSWORD: password
      ME_CONFIG_MONGODB_SERVER: mongodb

Dockerfile:

FROM node:13-alpine
ENV MONGO_DB_USERNAME=admin \
MONGO_DB_PWD=password
WORKDIR /app
COPY package.json .
RUN npm install
COPY . ./
EXPOSE 3000
CMD ["node","app.js"]

Html file:

<h1>Enquiry Form</h1>
    <div class="container">
        <div class="left">
            <div class="lef">
                <h2>Get in touch</h3>
                <form action="/sign_up" method="POST">
                    <div class="i1">
                        <input type="text" placeholder="Name" id="inp" class="border" name="name">
                    </div>
                    <div class="i1">
                        <input type="text" placeholder="Email" id="inp" class="border" name="email">
                    </div>
                    <div>
                        <input type="text" placeholder="Subject" id="inp2" class="border" name="subject">
                    </div>
                    <div>
                        <textarea placeholder="Message" cols="30" rows="10" id="inp3" class="border" name="message"></textarea>
                    </div>
                    <button class="btn border">Send Message</button>
                </form>
            </div>
        </div>
        <div class="right">
            <div class="lef">
                <h2 class="contact">Contact us</h2>
                <p><i class="fas fa-map-marker-alt symbol"></i> Address: 1234/1A.</p>
    
                <p><i class="fas fa-phone-alt symbol"></i> Phone: + 1235 2355 98</p>
    
                <p><i class="fas fa-envelope symbol"></i> Email: info@site.com</p>
    
                <p><i class="fab fa-github symbol"></i> GitHub: https://github.com</p>

                <p><i class="fab fa-linkedin symbol"></i> Linkedin: https://Linkedin.com</p>
            </div>
        </div>
    </div>

package.json file:

{
  "name": "RegistrationForm",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.19.0",
    "express": "^4.17.1",
    "mongodb": "^4.3.1",
    "nodemon": "^2.0.15"
  }
}

Getting this error after around 30sec

MongoServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
    at Timeout._onTimeout (/app/node_modules/mongodb/lib/sdam/topology.js:312:38) 
    at listOnTimeout (internal/timers.js:549:17)
    at processTimers (internal/timers.js:492:7) {
  reason: TopologyDescription {
    type: 'Unknown',
    servers: Map(1) { 'localhost:27017' => [ServerDescription] },
    stale: false,
    compatible: true,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    logicalSessionTimeoutMinutes: undefined
  }
}

Help me out please and thanks in advance :)

Rahul
  • 1
  • 1
  • What is your host OS? By the way, you should not hard-code your database credentials in your code – OneCricketeer Feb 06 '22 at 13:36
  • Windows 10 @OneCricketeer – Rahul Feb 07 '22 at 16:43
  • 1
    Did you install "Docker for Windows"? Or did you run something like `apt install docker` within WSL2? Only using the first option will properly forward ports. Related - https://stackoverflow.com/questions/70710592/cannot-connect-to-mongo-thats-inside-docker-inside-wsl2/70736511#70736511 – OneCricketeer Feb 08 '22 at 14:52

0 Answers0