SSH-ing into an app deployed on Cloudfoundry, for example to access a database service, is well documented:
- Accessing Apps with SSH, Cloudfoundry documentation
- Orgs, Spaces, Roles, and Permissions, Cloudfoundry documentation
- SSH Access Control Hierarchy, Cloudfoundry documentation
- Troubleshooting Guide on Configuring and Using CF SSH, Pivotal Community Page
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:
- Enable SSH for the space and check if it was enabled:
- Enable SSH for the app and check if it was enabled:
- Inconvenient but necessary: Restage the app:
- “Normal” SSH into app (for building up SSH to connect to a database, see below!)
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
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:
After getting the name of the app, the environmental variables can be displayed with
The variables “endpoint” and “port” are needed to establish the connection as follows:
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.