Moving your NodeJS Projects to Kubernetes in Bluemix

Binding Services Without Hassle

Move your NodeJS app from CloudFoundry to Kubernetes in Bluemix.

Background

We will discuss 3 scenarios: Your NodeJS app is using Watson services exclusively, your app is already using the vcap_services library, and your app is not currently using the vcap_services library. This post assumes you have a basic familiarity with NodeJS, Bluemix, and Kubernetes.

UPDATE: Due to some changes to the vcap_services library, fuzzy matching when specifying only the service name is no longer supported. As a result, for scenario 2 & 3 you should specify the <service_instance_name>. Scenario 1 can be handled as described in the linked article. We will work to find a solution that accommodates all use cases.

Scenario 1: Your app is using Watson services exclusively

If your app is exclusively using Watson services, and the watson-developer-cloud npm module, there is very little you need to change. In your Kubernetes YAML, simply bind the service to an environmental variable <SERVICE_NAME>_* (all upper case). For the simple conversation demo, this would look something like:

env:
- name: CONVERSATION_CAR
value_from:
secretKeyRef:
name: binding-conversation-car
key: binding

See the Bind a Watson Service to a Kubernetes Pod recipe for a more in-depth look at setting up Kubernetes and Waston.

Scenario 2: Your app is using the vcap_services module

If your app is already using the vcap_services library, things will work similarly to the previous example. Map your service to an environmental variable <SERVICE_NAME>_*, and invoke:

vcap_services.get_credentials(“<service_name>”);.

If you are using multiple instances of the same service, invoke:

get_credentials(“<service_name>”, null, “<service_instance_name>”);.

The system will look for an env var with the service instance name, and fall back on one that starts with the service name if that does not exist. Since service plan tier information is not given in these service instance bindings, that parameter is ignored. Note, if you only use the service_name method and have multiple environmental variables with JSON that start with the service name, you may get unexpected results.

Scenario 3: Your app is not currently using the vcap_services module

If your app does not use the vcap_services module, begin using it to get your service credentials. If you are using cfenv, then something like this:

var cfenv = require('cfenv');
var appEnv = cfenv.getAppEnv();
var service = appEnv.getService('service_name');
var service_username = service.credentials['username');

can be replaced by:

var vcapServices = require('vcap_services');
var credentials = vcapServices.getCredentials('service_name');
var service_username = credentials['username'];

Other CF_ENV variables will not be set in the Kubernetes environment, so other modifications may be needed if your app depends on these values.


Originally published at developer.ibm.com.