Connecting Nodejs Project to MongoDB using Laradock

30 Views Asked by At

I am trying to create a nextjs project with a mongodb database and use laradock. So far I have set up the configuration file for nginx with the project using reverse proxy but somehow I can't connect to the mongodb.

For context,

in the .env file of my laradock repo, I have set this value:

WORKSPACE_INSTALL_MONGO=true

PHP_FPM_INSTALL_MONGO=true

For the project, I've set the nginx/sites/*.conf like this

server {

    listen 80;
    listen [::]:80;

    #listen 443;
    #listen [::]:443;

    server_name sample.local;

    location / {
        proxy_pass http://workspace:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_cache_bypass $http_upgrade;
    }

    location ~ /\.ht {
        deny all;
    }

    location /.well-known/acme-challenge/ {
        root /var/www/letsencrypt/;
        log_not_found off;
    }

    error_log /var/log/nginx/node.com.co.local_error.log;
    access_log /var/log/nginx/node.com.co.local_access.log;
}

Then I run this in the terminal

cd <laradock_dir>
docker-compose up -d nginx workspace mongo
docker-compose exec workspace bash
cd <project_dir>
yarn run dev 

I can open the sample.local in browser, but I get CONNECTION REFUSE error when connecting it in mongodb

This is how I connect my project on mongodb

in my config/database.js I have:

const mongoose = require("mongoose");

mongoose.Promise = global.Promise;

const connect = async () => {
  mongoose.connect(`mongodb://localhost:27017/sample-db`, { useNewUrlParser: true, useUnifiedTopology: true });

  const db = mongoose.connection;
  db.on("error", () => {
    console.log("Cannot connect");
  });
  db.once("open", () => {
    console.log("Successfully connected");
  });
};
module.exports = { connect };

I can open the connection string mongodb://localhost:27017/ in the MongoDB Compass well, but I only get the connection refuse error when running it in the project.

What am I missing? Is this even possible? I just want to know if there is a way I could use the mongodb in my local machine only while still using laradock.

sorry if the details are a bit vogue, I'm still new at using laradock. If you need more details to help me solve this problem, please let me know.

Any help would be appreciated. :)

0

There are 0 best solutions below