SSH in app on Cloudfoundry, for example to access database service

Posted by Steven

SSH-ing into an app deployed on Cloudfoundry, for example to access a database service, is well documented:

Here's the general process:

1. SSH to an app in Cloudfoundry

Connecting to a database-service in a space is only possible from apps deployed in the same space. Hence, a local developer machine has to create an SSH-tunnel to an app like this:

1. Enable SSH for the space and check if it was enabled:

  1. cf allow-space-ssh myspace
  2. cf space-ssh-allowed myspace

2. Enable SSH for the app and check if it was enabled:

  1. cf enable-ssh myapp
  2. cf ssh-enabled myapp

3. Inconvenient but necessary: Restage the app:

  1. cf restage myapp

4. "Normal" SSH into app (for building up SSH to connect to a database, see below!)

  1. cf ssh myapp

Be aware that SSH-enabling of an app can be restricted, for example to be disconnected after one hour. After that, re-enabling SSH for the app is necessary.

Also, don't forget to restage the app. Without this step, you may get an

  1. Error opening SSH connection: ssh: handshake failed: ssh: unable to authenticate, attempted methods [none password], no supported methods remain

2. Connecting to a database service

In the example above, a normal SSH-tunnel to an application was created. To access a database, an additional port-forwarding has to be created. That way, the database in Cloudfoundry is tunneled through the SSH tunnel to be accessible from the local system.

First, the endpoint of the database service has to be copied from the VCAP_SERVICES variables of one of the apps that is bound to the service. Find out which app is bound to the database with:

  1. cf services

After getting the name of the app, the environmental variables can be displayed with

  1. cf env myapp

The variables "endpoint" and "port" are needed to establish the connection as follows:

  1. cf ssh myapp -L 1234:ENDPOINT:1234

With this, two things are happening: An SSH tunnel is established to the app and with that, the port-forwarding from the database to the local machine is created. The terminal must not be closed to keep the connection alive. Now, a local database tool can connect to localhost and the given port to be tunneled into Cloudfoundry.

Notice that multiple apps can be bound to one and the same database service and that each of those apps will have its own user and password for this service. Both of these credentials will work when accessing the database service.

Notice that because of the necessary restaging after enabling SSH for an application, it makes sense to deploy a dummy app that serves as the SSH endpoint and can be restarted without interrupting business processes.