Connecting to Deno MongoDb in Docker throws uncaught promise (in wsl2) - mongodb

The project runs in Deno.
I'm trying to connect the MongoClient in Deno to a MongoDb container running in Docker.
The docker container is running in wsl2 with the wsl ip 172.18.96.38 and exposing port 27017.
Connecting to it with the following code leads to an error:
import { MongoClient } from "https://deno.land/x/mongo#v0.23.0/mod.ts";
const uri = 'mongodb://admin:admin#172.18.96.38:27017'
this.mClient = new MongoClient();
await this.mClient.connect(uri);
error: Uncaught (in promise) Error: MongoError: "Connection failed: MongoError: {\"ok\":0,\"errmsg\":\"no such command: 'hello'\",\"code\":59,\"codeName\":\"CommandNotFound\"}"
throw new MongoError(`Connection failed: ${e.message || e}`);
^
at MongoClient.connect (https://deno.land/x/mongo#v0.23.0/src/client.ts:26:13)
at async Function.initMongoClient (file:///home/robert/repos/myDenoWebsite/backend/src/utils/mongoClientWrapper.ts:54:9)
According to the errmsg the error is 'no such command: 'hello'.
What does this mean?
This is my docker-compose.yml for mongo btw:
version: '3.8'
services:
mongodb:
image: mongo:4.4-bionic
container_name: my-mongodb
ports:
- 27017:27017
environment:
- MONGO_INITDB_ROOT_USERNAME=admin
- MONGO_INITDB_ROOT_PASSWORD=admin
volumes:
- mongodb:/data/db
- mongoconfig:/data/configdb
volumes:
mongodb:
mongoconfig:

I got a same error, so I found an alternative way
This is my solution
import { MongoClient } from "https://deno.land/x/mongo#v0.29.2/mod.ts";
const conn = async () => {
const client = new MongoClient();
const srv = `mongodb+srv://admin:admin#172.18.96.38:27017/<Your Database>?authMechanism=SCRAM-SHA-1&retryWrites=true&w=majority`
await client.connect(srv);
return client;
}
export const getData = async () => {
const conn = await conn()
<Your Logic Here>
}

Related

Cannot connect to MongoDB v6 in docker in ec2 after enabling SSL/TLS in .NET core app

I think I am bit confused on MongoDB v& in docker with TLS enabled. Everything seems to be working fine on the EC2 instance and also with those public key on my local MongoDB Compass tool.
But come to my .NET application, it is not connecting.
I have tried everything and I need some help with connection string.
Here is the code:
string conn = #"mongodb://username:Password#ec2instance.compute.amazonaws.com:27017/?tls=true&authMechanism=SCRAM-SHA-1";
var clientSettings = MongoClientSettings.FromUrl(new MongoUrl(conn));
clientSettings.AllowInsecureTls = true;
clientSettings.DirectConnection = true;
clientSettings.Scheme = ConnectionStringScheme.MongoDB;
clientSettings.UseTls = true;
clientSettings.ServerApi = new ServerApi(ServerApiVersion.V1);
SslSettings sslSettings = new SslSettings
{
ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true,
CheckCertificateRevocation = false,
EnabledSslProtocols = SslProtocols.Tls12,
ClientCertificates = new List<X509Certificate>() {
new X509Certificate2(AppDomain.CurrentDomain.BaseDirectory + #"Files\intermediate_pfx.pfx", "Phaseuser")
},
ClientCertificateSelectionCallback = (sender, host, certificates, certificate, issuers) => clientSettings.SslSettings.ClientCertificates.ToList()[0],
};
clientSettings.SslSettings = sslSettings;
MongoClient client = new MongoClient(clientSettings);
var dbList = client.ListDatabases().ToList();
And here is my compose.yaml file:
services:
mongo:
image: mongo
command: ["--bind_ip_all", "--tlsMode", "requireTLS", "--tlsCAFile", "/usr/local/ca-certificates/root_ca.crt", "--tlsCertificateKeyFile", "/run/secrets/server-certificate"]
environment:
MONGO_INITDB_ROOT_USERNAME: username
MONGO_INITDB_ROOT_PASSWORD: Password
restart: always
volumes:
- $PWD/ca-certs:/usr/local/ca-certificates
- $PWD/db:/data/db
secrets:
- server-certificate
ports:
- '27017-27019:27017-27019'
secrets:
server-certificate:
file: mongo.pem
Everytime when I tried to connect to it, its says timeout.
Any suggestions would be really helpful.

Flutter can not connect to the docker localhost parse-server

I am trying to run a parse-server and parse-dashboard via the following docker-compose.yml
docker-compose:
version: '3.9'
services:
database:
image: mongo:5.0
environment:
MONGO_INITDB_ROOT_USERNAME: admin
MONGO_INITDB_ROOT_PASSWORD: admin
volumes:
- data_volume:/data/mongodb
server:
restart: always
image: parseplatform/parse-server:4.10.4
ports:
- 1337:1337
environment:
- PARSE_SERVER_APPLICATION_ID=COOK_APP
- PARSE_SERVER_MASTER_KEY=MASTER_KEY_1
- PARSE_SERVER_CLIENT_KEY=CLIENT_KEY_1
- PARSE_SERVER_DATABASE_URI=mongodb://admin:admin#mongo/parse_server?authSource=admin
- PARSE_ENABLE_CLOUD_CODE=yes
links:
- database:mongo
volumes:
- data_volume:/data/server
- ./../lib/core/database/parse_server/cloud:/parse-server/cloud
dashboard:
image: parseplatform/parse-dashboard:4.0.0
ports:
- "4040:4040"
depends_on:
- server
restart: always
environment:
- PARSE_DASHBOARD_APP_ID=COOK_APP
- PARSE_DASHBOARD_MASTER_KEY=MASTER_KEY_1
- PARSE_DASHBOARD_USER_ID=admin
- PARSE_DASHBOARD_USER_PASSWORD=admin
- PARSE_DASHBOARD_ALLOW_INSECURE_HTTP=true
- PARSE_DASHBOARD_SERVER_URL=http://localhost:1337/parse
volumes:
- data_volume:/data/dashboard
volumes:
data_volume:
driver: local
After the container is running via docker-compose up I am trying to connect to it using Flutter and write a new class to my server:
Flutter code:
import 'package:flutter/material.dart';
import 'package:parse_server_sdk_flutter/parse_server_sdk.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
const keyApplicationId = 'COOK_APP';
const keyClientKey = 'CLIENT_KEY_1';
const keyParseServerUrl = 'http://localhost:1337/parse';
var res = await Parse().initialize(keyApplicationId, keyParseServerUrl,
clientKey: keyClientKey, autoSendSessionId: true);
var connRes = await res.healthCheck();
var s = connRes.error?.message ?? "";
print("ERROR:" + s);
var firstObject = ParseObject('FirstClass')
..set(
'message', 'Hey ! First message from Flutter. Parse is now connected');
await firstObject.save();
print('done');
}
My error message:
SocketException: Connection refused (OS Error: Connection refused, errno = 111), address = localhost, port = 35262
But for some unknown reason, I can not connect to my local server even if I can access with no problem my dashboard.
Your application running on the mobile device/emulator will treat localhost as own machine. In order to access the parse server running on your host machine (docker image exposing 0.0.0.0 global) you need to specify the host IP address.
Just replace const keyParseServerUrl = 'http://localhost:1337/parse'; with const keyParseServerUrl = 'http://YOUR_HOST_IP_ADDRESS:1337/parse'; provided in the docker parse server 0.0.0.0 should be exposed.

Deno Uncaught Error: No such host is known. (os error 11001)

I tried to connect the MongoDB Atlas to my Deno Application using https://deno.land/x/mongo#v0.21.2 framework. I tried the below code to run my application. but I get an error No such host is known. (os error 11001) What went wrong here
Error
error: Uncaught Error: No such host is known. (os error 11001)
at unwrapResponse (rt\10_dispatch_json.js:24:13)
at sendAsync (rt\10_dispatch_json.js:75:12)
at async Object.connect (rt\30_net.js:221:13)
at async MongoClient.connect (client.ts:41:14)
at async mongodb.ts:33:1
Mongodb.ts File
import { MongoClient } from "https://deno.land/x/mongo#v0.21.0/mod.ts";
const client1 = new MongoClient();
await client1.connect("mongodb+srv://user1:MYPASSWORD#cluster0.hmdnu.mongodb.net/TestingDB?retryWrites=true&w=majority");
const db = client1.database("TestingDB");
export default db;
I used this command to run my server
deno run --allow-net --allow-write --allow-read --allow-plugin --unstable server.ts
I fixed this using https://www.youtube.com/watch?v=hhdhydffKKE this video reference
Follow these steps to fix this
import { MongoClient } from "https://deno.land/x/mongo#v0.21.0/mod.ts";
const client1 = new MongoClient();
await client.connect({
db: "<db>",
tls: true,
servers: [
{
host: "<host>",
port: 27017,
},
],
credential: {
username: "<user>",
password: "<password>",
db: "<db>",
mechanism: "SCRAM-SHA-1",
},
});
const db = client1.database("TestingDB");
export default db;
This is not mentions in the document, but this will help to fix the issue
<db> is the database name, you can get the database name by following these steps
Step-1
Step-2
To find the <host> follow these steps
Step -1
Step -2
Step -3

Express app won't connect to docker postgres instance in production

I am building a webapp using express and postgres. For building my app I use the following files:
docker-compose.yml:
version: '3'
services:
postgres:
image: postgres:12
volumes:
- postgres-volume:/var/lib/postgresql/data
environment:
- POSTGRES_PASSWORD=${ADMIN_DB_PASSWORD}
networks:
- db
restart: unless-stopped
api:
build:
context: ./backEnd/
dockerfile: Dockerfile.debug
volumes:
- ./backEnd/index.js:/app/index.js
ports:
- "80:3002"
networks:
- db
depends_on:
- postgres
environment:
- DB_HOST=postgres
- DB_PORT=5432
- DB_DATABASE=hive
- DB_USER=${DB_API_USER}
- DB_PASSWORD=${DB_API_PASSWORD}
restart: unless-stopped
networks:
db:
The container runs the following code:
const express = require('express');
const bodyParser = require('body-parser')
const pgp = require('pg-promise')();
const connection = {
host: process.env.DB_HOST,
port: process.env.DB_PORT,
database: process.env.DB_DATABASE,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
max: 30,
}
const db = pgp(connection);
function getUser(email){
return(
db.oneOrNone("SELECT * FROM users WHERE email = ${email}", {
email:email.toLowerCase()
})
)
}
const app = express();
app.use(bodyParser.json());
app.post('/login', async (req, res)=>{
const email = req.body.email;
console.log(email)
const user = await getUser(email);
console.log("made it past")
});
app.listen(3002, function () {
console.log('Listening on port 3002!');
});
When I call the login endpoint, it faithfully logs the email, but never gets past the
await getUser(email)
It does not throw and error or returns null, it just stays there. Interestingly it is working on my local machine and gets past the await, just not on my linux box.
I have also noticed, that if I change the db host to something nonsensical, pg-promise throws an error on my local machine. It does not however throw an error on my remote linux machine.
Also, if I run the script on the Linux box, without docker, it seamlessly connects to postgres. It appears to be something that only happens in conjunction with docker on Linux.
I am completely stumped by this error, as I have no indication of what is going wrong. The database also appears to be set up correctly, as I can connect to it and use it from my local machine with the same code.
Thank you in advance for your help.

Issue while connecting JMeter to MongoDb: com.mongodb.CommandFailureException ... Authentication failed

This is how I am connecting successfully from Spring Data to MongoDb running on my local Docker:
aplication.yml:
spring:
data:
mongodb:
host: localhost
port: 27017
database: demodb
authentication-database: admin
username: root
password: rootpassword
Unfortunatelly I am stuck to connect from JMeter to same MongoDb. After several searches around I reached this Grovy Code (it is my first time using Grovy):
import com.mongodb.*
import com.mongodb.BasicDBObject
import org.bson.*
MongoCredential coreCredential = MongoCredential.createCredential("root", "demodb", "rootpassword".toCharArray());
MongoClient coreMongoClient = new MongoClient(new ServerAddress("localhost", 27017), Arrays.asList(coreCredential));
DB coreDB = coreMongoClient.getDB("demodb");
DBCollection coll = coreDB.getCollection("transfer");
BasicDBObject document = new BasicDBObject("id", "3")
.append("origem", "Jimis")
.append("destino", "drpc")
.append("status", 1);
coreDB.getCollection('transfer').insert(document);
Complete error:
-06 18:59:39,561 INFO o.a.j.t.JMeterThread: Thread started: Thread Group 1-1
2020-04-06 18:59:39,588 ERROR o.a.j.p.j.s.JSR223Sampler: Problem in JSR223 script JSR223 Sampler, message: javax.script.ScriptException: com.mongodb.CommandFailureException: { "serverUsed" : "localhost:27017" , "ok" : 0.0 , "errmsg" : "Authentication failed." , "code" : 18 , "codeName" : "AuthenticationFailed"}
javax.script.ScriptException: com.mongodb.CommandFailureException: { "serverUsed" : "localhost:27017" , "ok" : 0.0 , "errmsg" : "Authentication failed." , "code" : 18 , "codeName" : "AuthenticationFailed"}
at org.codehaus.groovy.jsr223.GroovyScriptEngineImpl.eval(GroovyScriptEngineImpl.java:324) ~[groovy-all-2.4.16.jar:2.4.16]
at org.codehaus.groovy.jsr223.GroovyCompiledScript.eval(GroovyCompiledScript.java:72) ~[groovy-all-2.4.16.jar:2.4.16]
at javax.script.CompiledScript.eval(CompiledScript.java:89) ~[java.scripting:?]
at org.apache.jmeter.util.JSR223TestElement.processFileOrScript(JSR223TestElement.java:223) ~[ApacheJMeter_core.jar:5.2.1]
at org.apache.jmeter.protocol.java.sampler.JSR223Sampler.sample(JSR223Sampler.java:71)
PS.: I read other stackoverflow answer I should update JMeter MongoDb jar so I did (now is mongo-java-driver-2.13.2.jar)
*** Edited trying third Dmitri's suggestion
import com.mongodb.*
MongoClient mongoClient = MongoClients.create('mongodb://root:rootpassword#localhost/?authSource=admin')
BasicDBObject document = new BasicDBObject("id", "5")
.append("origem", "Jimis")
.append("destino", "drpc")
.append("status", 1);
coreDB.getCollection('transfer').insert(document);
*** Added after taking care of first Dmitri's suggestion:
docker-compose.yml
version: '3.7'
services:
mongo-express:
image: mongo-express
ports:
- 8081:8081
environment:
ME_CONFIG_MONGODB_SERVER: mongo-db
ME_CONFIG_BASICAUTH_USERNAME: admin
ME_CONFIG_BASICAUTH_PASSWORD: q
ME_CONFIG_MONGODB_PORT: 27017
ME_CONFIG_MONGODB_ADMINUSERNAME: root
ME_CONFIG_MONGODB_ADMINPASSWORD: rootpassword
depends_on:
- mongo-db
networks:
- mongo-compose-network
mongo-db:
image: mongo:latest
environment:
MONGO_INITDB_DATABASE: demodb
MONGO_INITDB_ROOT_USERNAME: root
MONGO_INITDB_ROOT_PASSWORD: rootpassword
ports:
- "27017:27017"
volumes:
- mongodb_data_container:/data/db
networks:
- mongo-compose-network
networks:
mongo-compose-network:
driver: bridge
volumes:
mongodb_data_container:
*** FINAL SOLUTION
I guess I had done these groups of mistakes or one of them:
I did import especifically the class I want use. It seems import com.mongodb.* isn't working as I expected.
I didn't add the MongoDb Java Driver on lib/ext. Now I added in both lib and lib/ext folders
ssl = true probably is the most significant mistake since I am using Docker and I didn't open ssl
BTW, here is my solution for future readers:
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import java.util.Arrays;
//MongoClient mongoClient = MongoClients.create("mongodb://root:rootpassword#localhost:27017/?authSource=userdb&ssl=false");
//MongoClient mongoClient = MongoClients.create("mongodb://root:rootpassword#localhost:27017/?ssl=false");
MongoClient mongoClient = MongoClients.create("mongodb://root:rootpassword#localhost:27017");
MongoDatabase database = mongoClient.getDatabase("demodb");
MongoCollection<Document> collection = database.getCollection("transfer");
//Document document = new Document("firstName", "Expert")
//.append("lastName", "Protocolson")
//.append("age", 37)
//.append("occupation", "DevOps")
//.append("skills", Arrays.asList("System Administration", "Linux"))
//.append("address", new Document("city", "Systemberg")
//.append("street", "Data Line")
//.append("house", 42));
Document document = new Document("_id", 7)
.append("origem", "Jimis")
.append("destino", "drpc")
.append("valor", "999")
.append("status", 3);
collection.insertOne(document);
Not knowing the details of your MongoDB docker image it is not possible to provide a comprehensive answer, so far I can only think of the following next steps:
Ensure that your MongoDB Java Driver matches the version of your MongoDB server
You might need to explicitly add the user to your database in the Mongo Shell like:
db.createUser(
{
user: "root",
pwd: "rootpassword",
roles: [ { role: "dbOwner", db: "demodb" } ]
}
)
You can try out alternative approach of passing the credentials by embedding it into the MongoDB Connection String like
MongoClient mongoClient = MongoClients.create('mongodb://root:rootpassword#localhost/?authSource=admin')
More information: MongoDB Performance Testing with JMeter