Connecting to MongoDB Container on VM via SSH in Express.js App

41 Views Asked by At

i want on my local computer connect in my express.js app to the mongodb database with mongoose which runs on a remote server in a docker container in a docker network. The server is only accessable via ssh for me.

My last try was to use ssh2. I am able to connect to the server via ssh but i always get "MongooseServerSelectionError: getaddrinfo ENOTFOUND " or "MongoServerError: Authentication failed."

I already tried to use the server ip, localhost, 127.0.0.1, the name of the container in the network or the ip of the container inside the connection string for mongoose.

This is what i have:

const connectDB = async () => {
  try {
    if (process.env.NODE_ENV === "development") {
      const sshConfig = {
        username: process.env.VM_HOST,
        host: process.env.HOST_IP,
        port: 22,
        password: process.env.VM_PW,
      };
      const sshConnection = new Client();

      sshConnection.on('ready', () => {
        sshConnection.forwardOut(
          '127.0.0.1',
          27017,
          process.env.HOST_IP,
          27017,
          async (err, stream) => {
            if (err) {
              console.error('Error creating SSH tunnel:', err);
              process.exit(1);
            }
            console.log("connected!")
            try {
              const conn = await mongoose.connect(process.env.MONGO_URI, { dbName: 'dbname' })
              console.log(`MongoDB Connected : ${conn.connection.host}`.cyan.underline)
            }
            catch (error) {
              console.log(error)
              process.exit(1)
            }
          }
        );
      });

      sshConnection.connect(sshConfig);

      sshConnection.on('error', (err) => {
        console.error('SSH connection error:', err);
      });

      sshConnection.on('close', () => {
        console.log('SSH connection closed.');
      });
    } else if (process.env.NODE_ENV === "production") {
      try {
        const conn = await mongoose.connect(process.env.MONGO_URI, { dbName: 'dbname' })
        console.log(`MongoDB Connected : ${conn.connection.host}`.cyan.underline)
      }
      catch (error) {
        console.log(error)
        process.exit(1)
      }
    }
  } catch (error) {
    console.error('General error:', error);
    process.exit(1);
  }
};

TheMONGO_URI looks like this:

mongodb://<mongodbusername>:<mongodbpw>@<vm_ip/container_ip/localhost/127.0.0.1/container_name>:<mongodbport>/?authMechanism=DEFAULT&retryWrites=true&w=majority

I didn't use the '<>' in my code for sure.

Kinda the same i also tried with tunnel-ssh.

Anyone any idea?

Greetings

0

There are 0 best solutions below