To connect to a managed service instance on your Cloud Foundry space, most developers use service keys. A service key is a set of authentication credentials that allows you to connect to your database instance via a public IP address and port. While this is quick and easy to do, Meshcloud does not recommend keeping service keys open for extended periods of time. Instead, you should delete them as soon as possible and create a new service key anytime you need access again.

A more secure approach that does not involve exposing a connection to your database on a public IP is to spin up a shell container on Cloud Foundry and connect to it via cf ssh. This approach is also more suitable for long running or high performance operations that require close proximity between the database and the shell.

Here’s how to do it showcased for MongoDB, but a similar approach also works for our other managed services like MySQL or PostgreSQL.

1) Create an app named mongocli based on a docker container image containing the mongo cli. Tip: you can also specify a specific version using the appropriate container image tag, the example below uses :latest. Note that we tell Cloud Foundry that we need only very little RAM (128 MB), don’t want a health-check on the App and that it doesn’t need an HTTP route to be reachable from the outside. After all, we just want to ssh into this app.

cf push -o mongo:latest mongocli --no-route --no-start -u none -m 128M

2) Create a binding of the service instance to your new app. This makes a connection string available to the mongocli app that it can use to connect to the database instance on a private network, just like your proucution app does.

cf bind-service mongocli my-mongodb

3) Start the container, let it just run a bash

cf push -o mongo:latest mongocli --no-route -u none -m 128M -c bash

That’s it, now we can easily ssh into the container using cf ssh mongocli and run env to find our connection string in the VCAP_SERVICES variable. The connection string looks approximately like this:

VCAP_SERVICES={"MongoDB":[{
"credentials": {
"password": "abc",
"database": "db",
"uri": "mongodb://user:pw@ip1:27017,ip2:27017,ip3:27017/db",
"username": "xxx"
},
"syslog_drain_url": null,
"volume_mounts": [

],
"label": "MongoDB",
"provider": null,
"plan": "S",
"name": "my-mongodb",
"tags": [

]
}]}

Now you can simply run mongo mongodb://user:pw@ip1:27017,ip2:27017,ip3:27017/db and you’re securely connected to your managed database instance – on a docker container running mongo shell on Cloud Foundry – connected via ssh.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.