SSH in App on Cloudfoundry, for Example to access Database Service

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:
cf allow-space-ssh myspace
cf space-ssh-allowed myspace
  1. Enable SSH for the app and check if it was enabled:
cf enable-ssh myapp
cf ssh-enabled myapp
  1. Inconvenient but necessary: Restage the app:
cf restage myapp
  1. “Normal” SSH into app (for building up SSH to connect to a database, see below!)
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

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:

cf services

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

cf env myapp

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

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.