OpenShift Access Mongodb Pod from another Pod OpenShift Access Mongodb Pod from another Pod docker docker

OpenShift Access Mongodb Pod from another Pod


Ok that was a long search and finally I was able to solve it. My first mistake was, that routes are not suited to make a connection to a database as they only use the http-protocol.

Now there were 2 usecases left for me

  1. You're working on your local machine and want to test code that you later upload to OpenShift
  2. You deploy that code to OpenShift (has to be in the same project but is a different app than the database)

1. Local Machine

Since the route doesn't work port forwarding is used. I've read that before but didn't really understand what it meant (i thought the service itsself is forwading ports already).

When you are on your local machine you will do the following with the oc

oc port-forward <pod-name> <local-port>:<remote-port>

You'll get the info that the port is forwarded. Now the thing is, that in your app you will now connect to localhost (even on your local machine)

2. App running on OpenShift

After you will upload your code to OpenShift(In my case, just Add to project --> Node.js --> Add your repo), localhost will not be working any longer.What took a while for me to understand is that as long as you are in the same project you will have a lot of information in your environment variables.So just check the name of the service of your database (in my case mongodb) and you will find the host and port to use

Summary

Here's a little code example that works now, as well on the local machine as on OpenShift. I have already set up a persistand MongoDB on OpenShift called mongodb.

The code doesn't do much, but It will make a connection and tell you that it did, so you know it's working.

var mongoose = require('mongoose');// Connect to Mongodbvar username = process.env.MONGO_DB_USERNAME || 'someUserName';var password = process.env.MONGO_DB_PASSWORD || 'somePassword';var host = process.env.MONGODB_SERVICE_HOST || '127.0.0.1';var port = process.env.MONGODB_SERVICE_PORT || '27017';var database = process.env.MONGO_DB_DATABASE || 'sampledb';console.log('---DATABASE PARAMETERS---');console.log('Host: ' + host);console.log('Port: ' + port);console.log('Username: ' + username);console.log('Password: ' + password); console.log('Database: ' + database);var connectionString = 'mongodb://' + username + ':' + password +'@' + host + ':' + port + '/' + database;console.log('---CONNECTING TO---');console.log(connectionString);mongoose.connect(connectionString);mongoose.connection.once('open', (data) => {    console.log('Connection has been made');    console.log(data);});