Chapter 5. Example applications for Node.js
The Node.js runtime provides example applications. When you start developing applications on OpenShift, you can use the example applications as templates.
You can access these example applications on Developer Launcher.
You can download and deploy all the example applications on:
- x86_64 architecture - The example applications in this guide demonstrate how to build and deploy example applications on x86_64 architecture.
- s390x architecture - To deploy the example applications on OpenShift environments provisioned on IBM Z infrastructure, specify the relevant IBM Z image name in the commands.
- ppc64le architecture - To deploy the example applications on OpenShift environments provisioned on IBM Power Systems infrastructure, specify the relevant IBM Power Systems image name in the commands. - Some of the example applications also require other products, such as Red Hat Data Grid to demonstrate the workflows. In this case, you must also change the image names of these products to their relevant IBM Z or IBM Power Systems image names in the YAML file of the example applications. 
5.1. REST API Level 0 example for Node.js
The following example is not meant to be run in a production environment.
Example proficiency level: Foundational.
What the REST API Level 0 example does
The REST API Level 0 example shows how to map business operations to a remote procedure call endpoint over HTTP using a REST framework. This corresponds to Level 0 in the Richardson Maturity Model. Creating an HTTP endpoint using REST and its underlying principles to define your API lets you quickly prototype and design the API flexibly.
This example introduces the mechanics of interacting with a remote service using the HTTP protocol. It allows you to:
- 
						Execute an HTTP GETrequest on theapi/greetingendpoint.
- 
						Receive a response in JSON format with a payload consisting of the Hello, World!String.
- 
						Execute an HTTP GETrequest on theapi/greetingendpoint while passing in a String argument. This uses thenamerequest parameter in the query string.
- 
						Receive a response in JSON format with a payload of Hello, $name!with$namereplaced by the value of thenameparameter passed into the request.
5.1.1. REST API Level 0 design tradeoffs
| Pros | Cons | 
|---|---|
| 
 | 
 | 
5.1.2. Deploying the REST API Level 0 example application to OpenShift Online
Use one of the following options to execute the REST API Level 0 example application on OpenShift Online.
					Although each method uses the same oc commands to deploy your application, using developers.redhat.com/launch provides an automated deployment workflow that executes the oc commands for you.
				
5.1.2.1. Deploying the example application using developers.redhat.com/launch
This section shows you how to build your REST API Level 0 example application and deploy it to OpenShift from the Red Hat Developer Launcher web interface.
Prerequisites
- An account at OpenShift Online.
Procedure
- Navigate to the developers.redhat.com/launch URL in a browser.
- Follow on-screen instructions to create and launch your example application in Node.js.
5.1.2.2. Authenticating the oc CLI client
						To work with example applications on OpenShift Online using the oc command-line client, you must authenticate the client using the token provided by the OpenShift Online web interface.
					
Prerequisites
- An account at OpenShift Online.
Procedure
- Navigate to the OpenShift Online URL in a browser.
- Click on the question mark icon in the top right-hand corner of the Web console, next to your user name.
- Select Command Line Tools in the drop-down menu.
- 
								Copy the oc logincommand.
- Paste the command in a terminal. The command uses your authentication token to authenticate your - ocCLI client with your OpenShift Online account.- oc login OPENSHIFT_URL --token=MYTOKEN - $ oc login OPENSHIFT_URL --token=MYTOKEN- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
5.1.2.3. Deploying the REST API Level 0 example application using the oc CLI client
This section shows you how to build your REST API Level 0 example application and deploy it to OpenShift from the command line.
Prerequisites
- The example application created using developers.redhat.com/launch. For more information, see Section 5.1.2.1, “Deploying the example application using developers.redhat.com/launch”.
- 
								The occlient authenticated. For more information, see Section 5.1.2.2, “Authenticating theocCLI client”.
Procedure
- Clone your project from GitHub. - git clone git@github.com:USERNAME/MY_PROJECT_NAME.git - $ git clone git@github.com:USERNAME/MY_PROJECT_NAME.git- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - Alternatively, if you downloaded a ZIP file of your project, extract it. - unzip MY_PROJECT_NAME.zip - $ unzip MY_PROJECT_NAME.zip- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
- Create a new project in OpenShift. - oc new-project MY_PROJECT_NAME - $ oc new-project MY_PROJECT_NAME- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
- Navigate to the root directory of your application.
- Use - npmto start the deployment to OpenShift.- npm install && npm run openshift - $ npm install && npm run openshift- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - These commands install any missing module dependencies, then using the Nodeshift module, deploy the example application on OpenShift. 
- Check the status of your application and ensure your pod is running. - oc get pods -w - $ oc get pods -w NAME READY STATUS RESTARTS AGE MY_APP_NAME-1-aaaaa 1/1 Running 0 58s MY_APP_NAME-s2i-1-build 0/1 Completed 0 2m- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - The - MY_APP_NAME-1-aaaaapod should have a status of- Runningonce it is fully deployed and started. Your specific pod name will vary. The number in the middle will increase with each new build. The letters at the end are generated when the pod is created.
- After your example application is deployed and started, determine its route. - Example Route Information - oc get routes - $ oc get routes NAME HOST/PORT PATH SERVICES PORT TERMINATION MY_APP_NAME MY_APP_NAME-MY_PROJECT_NAME.OPENSHIFT_HOSTNAME MY_APP_NAME 8080- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - The route information of a pod gives you the base URL which you use to access it. In the example above, you would use - http://MY_APP_NAME-MY_PROJECT_NAME.OPENSHIFT_HOSTNAMEas the base URL to access the application.
5.1.3. Deploying the REST API Level 0 example application to Minishift or CDK
Use one of the following options to execute the REST API Level 0 example application locally on Minishift or CDK:
					Although each method uses the same oc commands to deploy your application, using Fabric8 Launcher provides an automated deployment workflow that executes the oc commands for you.
				
5.1.3.1. Getting the Fabric8 Launcher tool URL and credentials
You need the Fabric8 Launcher tool URL and user credentials to create and deploy example applications on Minishift or CDK. This information is provided when the Minishift or CDK is started.
Prerequisites
- The Fabric8 Launcher tool installed, configured, and running.
Procedure
- Navigate to the console where you started Minishift or CDK.
- Check the console output for the URL and user credentials you can use to access the running Fabric8 Launcher: - Example Console Output from a Minishift or CDK Startup - Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
5.1.3.2. Deploying the example application using the Fabric8 Launcher tool
This section shows you how to build your REST API Level 0 example application and deploy it to OpenShift from the Fabric8 Launcher web interface.
Prerequisites
- The URL of your running Fabric8 Launcher instance and the user credentials of your Minishift or CDK. For more information, see Section 5.1.3.1, “Getting the Fabric8 Launcher tool URL and credentials”.
Procedure
- Navigate to the Fabric8 Launcher URL in a browser.
- Follow the on-screen instructions to create and launch your example application in Node.js.
5.1.3.3. Authenticating the oc CLI client
						To work with example applications on Minishift or CDK using the oc command-line client, you must authenticate the client using the token provided by the Minishift or CDK web interface.
					
Prerequisites
- The URL of your running Fabric8 Launcher instance and the user credentials of your Minishift or CDK. For more information, see Section 5.1.3.1, “Getting the Fabric8 Launcher tool URL and credentials”.
Procedure
- Navigate to the Minishift or CDK URL in a browser.
- Click on the question mark icon in the top right-hand corner of the Web console, next to your user name.
- Select Command Line Tools in the drop-down menu.
- 
								Copy the oc logincommand.
- Paste the command in a terminal. The command uses your authentication token to authenticate your - ocCLI client with your Minishift or CDK account.- oc login OPENSHIFT_URL --token=MYTOKEN - $ oc login OPENSHIFT_URL --token=MYTOKEN- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
5.1.3.4. Deploying the REST API Level 0 example application using the oc CLI client
This section shows you how to build your REST API Level 0 example application and deploy it to OpenShift from the command line.
Prerequisites
- The example application created using Fabric8 Launcher tool on a Minishift or CDK. For more information, see Section 5.1.3.2, “Deploying the example application using the Fabric8 Launcher tool”.
- Your Fabric8 Launcher tool URL.
- 
								The occlient authenticated. For more information, see Section 5.1.3.3, “Authenticating theocCLI client”.
Procedure
- Clone your project from GitHub. - git clone git@github.com:USERNAME/MY_PROJECT_NAME.git - $ git clone git@github.com:USERNAME/MY_PROJECT_NAME.git- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - Alternatively, if you downloaded a ZIP file of your project, extract it. - unzip MY_PROJECT_NAME.zip - $ unzip MY_PROJECT_NAME.zip- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
- Create a new project in OpenShift. - oc new-project MY_PROJECT_NAME - $ oc new-project MY_PROJECT_NAME- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
- Navigate to the root directory of your application.
- Use - npmto start the deployment to OpenShift.- npm install && npm run openshift - $ npm install && npm run openshift- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - These commands install any missing module dependencies, then using the Nodeshift module, deploy the example application on OpenShift. 
- Check the status of your application and ensure your pod is running. - oc get pods -w - $ oc get pods -w NAME READY STATUS RESTARTS AGE MY_APP_NAME-1-aaaaa 1/1 Running 0 58s MY_APP_NAME-s2i-1-build 0/1 Completed 0 2m- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - The - MY_APP_NAME-1-aaaaapod should have a status of- Runningonce it is fully deployed and started. Your specific pod name will vary. The number in the middle will increase with each new build. The letters at the end are generated when the pod is created.
- After your example application is deployed and started, determine its route. - Example Route Information - oc get routes - $ oc get routes NAME HOST/PORT PATH SERVICES PORT TERMINATION MY_APP_NAME MY_APP_NAME-MY_PROJECT_NAME.OPENSHIFT_HOSTNAME MY_APP_NAME 8080- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - The route information of a pod gives you the base URL which you use to access it. In the example above, you would use - http://MY_APP_NAME-MY_PROJECT_NAME.OPENSHIFT_HOSTNAMEas the base URL to access the application.
5.1.4. Deploying the REST API Level 0 example application to OpenShift Container Platform
The process of creating and deploying example applications to OpenShift Container Platform is similar to OpenShift Online:
Prerequisites
- The example application created using developers.redhat.com/launch.
Procedure
- Follow the instructions in Section 5.1.2, “Deploying the REST API Level 0 example application to OpenShift Online”, only use the URL and user credentials from the OpenShift Container Platform Web Console.
5.1.5. Interacting with the unmodified REST API Level 0 example application for Node.js
The example provides a default HTTP endpoint that accepts GET requests.
Prerequisites
- Your application running
- 
							The curlbinary or a web browser
Procedure
- Use - curlto execute a- GETrequest against the example. You can also use a browser to do this.- curl http://MY_APP_NAME-MY_PROJECT_NAME.OPENSHIFT_HOSTNAME/api/greeting - $ curl http://MY_APP_NAME-MY_PROJECT_NAME.OPENSHIFT_HOSTNAME/api/greeting {"content":"Hello, World!"}- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
- Use - curlto execute a- GETrequest with the- nameURL parameter against the example. You can also use a browser to do this.- curl http://MY_APP_NAME-MY_PROJECT_NAME.OPENSHIFT_HOSTNAME/api/greeting?name=Sarah - $ curl http://MY_APP_NAME-MY_PROJECT_NAME.OPENSHIFT_HOSTNAME/api/greeting?name=Sarah {"content":"Hello, Sarah!"}- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
						From a browser, you can also use a form provided by the example to perform these same interactions. The form is located at the root of the project http://MY_APP_NAME-MY_PROJECT_NAME.OPENSHIFT_HOSTNAME.
					
5.1.6. REST resources
More background and related information on REST can be found here:
5.2. Externalized Configuration example for Node.js
The following example is not meant to be run in a production environment.
Example proficiency level: Foundational.
Externalized Configuration provides a basic example of using a ConfigMap to externalize configuration. ConfigMap is an object used by OpenShift to inject configuration data as simple key and value pairs into one or more Linux containers while keeping the containers independent of OpenShift.
This example shows you how to:
- 
						Set up and configure a ConfigMap.
- 
						Use the configuration provided by the ConfigMapwithin an application.
- 
						Deploy changes to the ConfigMapconfiguration of running applications.
5.2.1. The externalized configuration design pattern
Whenever possible, externalize the application configuration and separate it from the application code. This allows the application configuration to change as it moves through different environments, but leaves the code unchanged. Externalizing the configuration also keeps sensitive or internal information out of your code base and version control. Many languages and application servers provide environment variables to support externalizing an application’s configuration.
Microservices architectures and multi-language (polyglot) environments add a layer of complexity to managing an application’s configuration. Applications consist of independent, distributed services, and each can have its own configuration. Keeping all configuration data synchronized and accessible creates a maintenance challenge.
ConfigMaps enable the application configuration to be externalized and used in individual Linux containers and pods on OpenShift. You can create a ConfigMap object in a variety of ways, including using a YAML file, and inject it into the Linux container. ConfigMaps also allow you to group and scale sets of configuration data. This lets you configure a large number of environments beyond the basic Development, Stage, and Production. You can find more information about ConfigMaps in the OpenShift documentation.
5.2.2. Externalized Configuration design tradeoffs
| Pros | Cons | 
|---|---|
| 
 | 
 | 
5.2.3. Deploying the Externalized Configuration example application to OpenShift Online
Use one of the following options to execute the Externalized Configuration example application on OpenShift Online.
					Although each method uses the same oc commands to deploy your application, using developers.redhat.com/launch provides an automated deployment workflow that executes the oc commands for you.
				
5.2.3.1. Deploying the example application using developers.redhat.com/launch
This section shows you how to build your REST API Level 0 example application and deploy it to OpenShift from the Red Hat Developer Launcher web interface.
Prerequisites
- An account at OpenShift Online.
Procedure
- Navigate to the developers.redhat.com/launch URL in a browser.
- Follow on-screen instructions to create and launch your example application in Node.js.
5.2.3.2. Authenticating the oc CLI client
						To work with example applications on OpenShift Online using the oc command-line client, you must authenticate the client using the token provided by the OpenShift Online web interface.
					
Prerequisites
- An account at OpenShift Online.
Procedure
- Navigate to the OpenShift Online URL in a browser.
- Click on the question mark icon in the top right-hand corner of the Web console, next to your user name.
- Select Command Line Tools in the drop-down menu.
- 
								Copy the oc logincommand.
- Paste the command in a terminal. The command uses your authentication token to authenticate your - ocCLI client with your OpenShift Online account.- oc login OPENSHIFT_URL --token=MYTOKEN - $ oc login OPENSHIFT_URL --token=MYTOKEN- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
5.2.3.3. Deploying the Externalized Configuration example application using the oc CLI client
This section shows you how to build your Externalized Configuration example application and deploy it to OpenShift from the command line.
Prerequisites
- The example application created using developers.redhat.com/launch. For more information, see Section 5.2.3.1, “Deploying the example application using developers.redhat.com/launch”.
- 
								The occlient authenticated. For more information, see Section 5.2.3.2, “Authenticating theocCLI client”.
Procedure
- Clone your project from GitHub. - git clone git@github.com:USERNAME/MY_PROJECT_NAME.git - $ git clone git@github.com:USERNAME/MY_PROJECT_NAME.git- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - Alternatively, if you downloaded a ZIP file of your project, extract it. - unzip MY_PROJECT_NAME.zip - $ unzip MY_PROJECT_NAME.zip- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
- Create a new OpenShift project. - oc new-project MY_PROJECT_NAME - $ oc new-project MY_PROJECT_NAME- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
- Assign view access rights to the service account before deploying your example application, so that the application can access the OpenShift API in order to read the contents of the ConfigMap. - oc policy add-role-to-user view -n $(oc project -q) -z default - $ oc policy add-role-to-user view -n $(oc project -q) -z default- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
- Navigate to the root directory of your application.
- Deploy your ConfigMap configuration to OpenShift using - app-config.yml.- oc create configmap app-config --from-file=app-config.yml - $ oc create configmap app-config --from-file=app-config.yml- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
- Verify your ConfigMap configuration has been deployed. - Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
- Use - npmto start the deployment to OpenShift.- npm install && npm run openshift - $ npm install && npm run openshift- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - These commands install any missing module dependencies, then using the Nodeshift module, deploy the example application on OpenShift. 
- Check the status of your application and ensure your pod is running. - oc get pods -w - $ oc get pods -w NAME READY STATUS RESTARTS AGE MY_APP_NAME-1-aaaaa 1/1 Running 0 58s MY_APP_NAME-s2i-1-build 0/1 Completed 0 2m- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - The - MY_APP_NAME-1-aaaaapod should have a status of- Runningonce its fully deployed and started. Your specific pod name will vary. The number in the middle will increase with each new build. The letters at the end are generated when the pod is created.
- After your example application is deployed and started, determine its route. - Example Route Information - oc get routes - $ oc get routes NAME HOST/PORT PATH SERVICES PORT TERMINATION MY_APP_NAME MY_APP_NAME-MY_PROJECT_NAME.OPENSHIFT_HOSTNAME MY_APP_NAME 8080- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - The route information of a pod gives you the base URL which you use to access it. In the example above, you would use - http://MY_APP_NAME-MY_PROJECT_NAME.OPENSHIFT_HOSTNAMEas the base URL to access the application.
5.2.4. Deploying the Externalized Configuration example application to Minishift or CDK
Use one of the following options to execute the Externalized Configuration example application locally on Minishift or CDK:
					Although each method uses the same oc commands to deploy your application, using Fabric8 Launcher provides an automated deployment workflow that executes the oc commands for you.
				
5.2.4.1. Getting the Fabric8 Launcher tool URL and credentials
You need the Fabric8 Launcher tool URL and user credentials to create and deploy example applications on Minishift or CDK. This information is provided when the Minishift or CDK is started.
Prerequisites
- The Fabric8 Launcher tool installed, configured, and running.
Procedure
- Navigate to the console where you started Minishift or CDK.
- Check the console output for the URL and user credentials you can use to access the running Fabric8 Launcher: - Example Console Output from a Minishift or CDK Startup - Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
5.2.4.2. Deploying the example application using the Fabric8 Launcher tool
This section shows you how to build your REST API Level 0 example application and deploy it to OpenShift from the Fabric8 Launcher web interface.
Prerequisites
- The URL of your running Fabric8 Launcher instance and the user credentials of your Minishift or CDK. For more information, see Section 5.2.4.1, “Getting the Fabric8 Launcher tool URL and credentials”.
Procedure
- Navigate to the Fabric8 Launcher URL in a browser.
- Follow the on-screen instructions to create and launch your example application in Node.js.
5.2.4.3. Authenticating the oc CLI client
						To work with example applications on Minishift or CDK using the oc command-line client, you must authenticate the client using the token provided by the Minishift or CDK web interface.
					
Prerequisites
- The URL of your running Fabric8 Launcher instance and the user credentials of your Minishift or CDK. For more information, see Section 5.2.4.1, “Getting the Fabric8 Launcher tool URL and credentials”.
Procedure
- Navigate to the Minishift or CDK URL in a browser.
- Click on the question mark icon in the top right-hand corner of the Web console, next to your user name.
- Select Command Line Tools in the drop-down menu.
- 
								Copy the oc logincommand.
- Paste the command in a terminal. The command uses your authentication token to authenticate your - ocCLI client with your Minishift or CDK account.- oc login OPENSHIFT_URL --token=MYTOKEN - $ oc login OPENSHIFT_URL --token=MYTOKEN- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
5.2.4.4. Deploying the Externalized Configuration example application using the oc CLI client
This section shows you how to build your Externalized Configuration example application and deploy it to OpenShift from the command line.
Prerequisites
- The example application created using Fabric8 Launcher tool on a Minishift or CDK. For more information, see Section 5.2.4.2, “Deploying the example application using the Fabric8 Launcher tool”.
- Your Fabric8 Launcher tool URL.
- 
								The occlient authenticated. For more information, see Section 5.2.4.3, “Authenticating theocCLI client”.
Procedure
- Clone your project from GitHub. - git clone git@github.com:USERNAME/MY_PROJECT_NAME.git - $ git clone git@github.com:USERNAME/MY_PROJECT_NAME.git- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - Alternatively, if you downloaded a ZIP file of your project, extract it. - unzip MY_PROJECT_NAME.zip - $ unzip MY_PROJECT_NAME.zip- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
- Create a new OpenShift project. - oc new-project MY_PROJECT_NAME - $ oc new-project MY_PROJECT_NAME- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
- Assign view access rights to the service account before deploying your example application, so that the application can access the OpenShift API in order to read the contents of the ConfigMap. - oc policy add-role-to-user view -n $(oc project -q) -z default - $ oc policy add-role-to-user view -n $(oc project -q) -z default- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
- Navigate to the root directory of your application.
- Deploy your ConfigMap configuration to OpenShift using - app-config.yml.- oc create configmap app-config --from-file=app-config.yml - $ oc create configmap app-config --from-file=app-config.yml- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
- Verify your ConfigMap configuration has been deployed. - Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
- Use - npmto start the deployment to OpenShift.- npm install && npm run openshift - $ npm install && npm run openshift- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - These commands install any missing module dependencies, then using the Nodeshift module, deploy the example application on OpenShift. 
- Check the status of your application and ensure your pod is running. - oc get pods -w - $ oc get pods -w NAME READY STATUS RESTARTS AGE MY_APP_NAME-1-aaaaa 1/1 Running 0 58s MY_APP_NAME-s2i-1-build 0/1 Completed 0 2m- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - The - MY_APP_NAME-1-aaaaapod should have a status of- Runningonce its fully deployed and started. Your specific pod name will vary. The number in the middle will increase with each new build. The letters at the end are generated when the pod is created.
- After your example application is deployed and started, determine its route. - Example Route Information - oc get routes - $ oc get routes NAME HOST/PORT PATH SERVICES PORT TERMINATION MY_APP_NAME MY_APP_NAME-MY_PROJECT_NAME.OPENSHIFT_HOSTNAME MY_APP_NAME 8080- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - The route information of a pod gives you the base URL which you use to access it. In the example above, you would use - http://MY_APP_NAME-MY_PROJECT_NAME.OPENSHIFT_HOSTNAMEas the base URL to access the application.
5.2.5. Deploying the Externalized Configuration example application to OpenShift Container Platform
The process of creating and deploying example applications to OpenShift Container Platform is similar to OpenShift Online:
Prerequisites
- The example application created using developers.redhat.com/launch.
Procedure
- Follow the instructions in Section 5.2.3, “Deploying the Externalized Configuration example application to OpenShift Online”, only use the URL and user credentials from the OpenShift Container Platform Web Console.
5.2.6. Interacting with the unmodified Externalized Configuration example application for Node.js
					The example provides a default HTTP endpoint that accepts GET requests.
				
Prerequisites
- Your application running
- 
							The curlbinary or a web browser
Procedure
- Use - curlto execute a- GETrequest against the example. You can also use a browser to do this.- curl http://MY_APP_NAME-MY_PROJECT_NAME.OPENSHIFT_HOSTNAME/api/greeting - $ curl http://MY_APP_NAME-MY_PROJECT_NAME.OPENSHIFT_HOSTNAME/api/greeting {"content":"Hello, World from a ConfigMap !"}- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
- Update the deployed ConfigMap configuration. - oc edit configmap app-config - $ oc edit configmap app-config- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - Change the value for the - messagekey to- Bonjour, %s from a ConfigMap !and save the file.
- Update of the ConfigMap should be read by the application within an acceptable time (a few seconds) without requiring a restart of the application.
- Execute a - GETrequest using- curlagainst the example with the updated ConfigMap configuration to see your updated greeting. You can also do this from your browser using the web form provided by the application.- curl http://MY_APP_NAME-MY_PROJECT_NAME.OPENSHIFT_HOSTNAME/api/greeting - $ curl http://MY_APP_NAME-MY_PROJECT_NAME.OPENSHIFT_HOSTNAME/api/greeting {"content":"Bonjour, World from a ConfigMap !"}- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
5.2.7. Externalized Configuration resources
More background and related information on Externalized Configuration and ConfigMap can be found here:
5.3. Relational Database Backend example for Node.js
The following example is not meant to be run in a production environment.
Limitation: Run this example application on a Minishift or CDK. You can also use a manual workflow to deploy this example to OpenShift Online Pro and OpenShift Container Platform. This example is not currently available on OpenShift Online Starter.
Example proficiency level: Foundational.
What the Relational Database Backend example does
The Relational Database Backend example expands on the REST API Level 0 application to provide a basic example of performing create, read, update and delete (CRUD) operations on a PostgreSQL database using a simple HTTP API. CRUD operations are the four basic functions of persistent storage, widely used when developing an HTTP API dealing with a database.
The example also demonstrates the ability of the HTTP application to locate and connect to a database in OpenShift. Each runtime shows how to implement the connectivity solution best suited in the given case. The runtime can choose between options such as using JDBC, JPA, or accessing ORM APIs directly.
				The example application exposes an HTTP API, which provides endpoints that allow you to manipulate data by performing CRUD operations over HTTP. The CRUD operations are mapped to HTTP Verbs. The API uses JSON formatting to receive requests and return responses to the user. The user can also use a user interface provided by the example to use the application. Specifically, this example provides an application that allows you to:
			
- 
						Navigate to the application web interface in your browser. This exposes a simple website allowing you to perform CRUD operations on the data in the my_datadatabase.
- 
						Execute an HTTP GETrequest on theapi/fruitsendpoint.
- Receive a response formatted as a JSON array containing the list of all fruits in the database.
- 
						Execute an HTTP GETrequest on theapi/fruits/*endpoint while passing in a valid item ID as an argument.
- Receive a response in JSON format containing the name of the fruit with the given ID. If no item matches the specified ID, the call results in an HTTP error 404.
- 
						Execute an HTTP POSTrequest on theapi/fruitsendpoint passing in a validnamevalue to create a new entry in the database.
- 
						Execute an HTTP PUTrequest on theapi/fruits/*endpoint passing in a valid ID and a name as an argument. This updates the name of the item with the given ID to match the name specified in your request.
- 
						Execute an HTTP DELETErequest on theapi/fruits/*endpoint, passing in a valid ID as an argument. This removes the item with the specified ID from the database and returns an HTTP code204(No Content) as a response. If you pass in an invalid ID, the call results in an HTTP error404.
This example does not showcase a fully matured RESTful model (level 3), but it does use compatible HTTP verbs and status, following the recommended HTTP API practices.
5.3.1. Relational Database Backend design tradeoffs
| Pros | Cons | 
|---|---|
| 
 | 
 | 
5.3.2. Deploying the Relational Database Backend example application to OpenShift Online
Use one of the following options to execute the Relational Database Backend example application on OpenShift Online.
					Although each method uses the same oc commands to deploy your application, using developers.redhat.com/launch provides an automated deployment workflow that executes the oc commands for you.
				
5.3.2.1. Deploying the example application using developers.redhat.com/launch
This section shows you how to build your REST API Level 0 example application and deploy it to OpenShift from the Red Hat Developer Launcher web interface.
Prerequisites
- An account at OpenShift Online.
Procedure
- Navigate to the developers.redhat.com/launch URL in a browser.
- Follow on-screen instructions to create and launch your example application in Node.js.
5.3.2.2. Authenticating the oc CLI client
						To work with example applications on OpenShift Online using the oc command-line client, you must authenticate the client using the token provided by the OpenShift Online web interface.
					
Prerequisites
- An account at OpenShift Online.
Procedure
- Navigate to the OpenShift Online URL in a browser.
- Click on the question mark icon in the top right-hand corner of the Web console, next to your user name.
- Select Command Line Tools in the drop-down menu.
- 
								Copy the oc logincommand.
- Paste the command in a terminal. The command uses your authentication token to authenticate your - ocCLI client with your OpenShift Online account.- oc login OPENSHIFT_URL --token=MYTOKEN - $ oc login OPENSHIFT_URL --token=MYTOKEN- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
5.3.2.3. Deploying the Relational Database Backend example application using the oc CLI client
This section shows you how to build your Relational Database Backend example application and deploy it to OpenShift from the command line.
Prerequisites
- The example application created using developers.redhat.com/launch. For more information, see Section 5.3.2.1, “Deploying the example application using developers.redhat.com/launch”.
- 
								The occlient authenticated. For more information, see Section 5.3.2.2, “Authenticating theocCLI client”.
Procedure
- Clone your project from GitHub. - git clone git@github.com:USERNAME/MY_PROJECT_NAME.git - $ git clone git@github.com:USERNAME/MY_PROJECT_NAME.git- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - Alternatively, if you downloaded a ZIP file of your project, extract it. - unzip MY_PROJECT_NAME.zip - $ unzip MY_PROJECT_NAME.zip- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
- Create a new OpenShift project. - oc new-project MY_PROJECT_NAME - $ oc new-project MY_PROJECT_NAME- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
- Navigate to the root directory of your application.
- Deploy the PostgreSQL database to OpenShift. Ensure that you use the following values for user name, password, and database name when creating your database application. The example application is pre-configured to use these values. Using different values prevents your application from integrating with the database. - oc new-app -e POSTGRESQL_USER=luke -ePOSTGRESQL_PASSWORD=secret -ePOSTGRESQL_DATABASE=my_data registry.access.redhat.com/rhscl/postgresql-10-rhel7 --name=my-database - $ oc new-app -e POSTGRESQL_USER=luke -ePOSTGRESQL_PASSWORD=secret -ePOSTGRESQL_DATABASE=my_data registry.access.redhat.com/rhscl/postgresql-10-rhel7 --name=my-database- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
- Check the status of your database and ensure the pod is running. - oc get pods -w - $ oc get pods -w my-database-1-aaaaa 1/1 Running 0 45s my-database-1-deploy 0/1 Completed 0 53s- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - The - my-database-1-aaaaapod should have a status of- Runningand should be indicated as ready once it is fully deployed and started. Your specific pod name will vary. The number in the middle will increase with each new build. The letters at the end are generated when the pod is created.
- Use - npmto start the deployment to OpenShift.- npm install && npm run openshift - $ npm install && npm run openshift- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - These commands install any missing module dependencies, then using the Nodeshift module, deploy the example application on OpenShift. 
- Check the status of your application and ensure your pod is running. - oc get pods -w - $ oc get pods -w NAME READY STATUS RESTARTS AGE MY_APP_NAME-1-aaaaa 1/1 Running 0 58s MY_APP_NAME-s2i-1-build 0/1 Completed 0 2m- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - Your - MY_APP_NAME-1-aaaaapod should have a status of- Runningand should be indicated as ready once it is fully deployed and started.
- After your example application is deployed and started, determine its route. - Example Route Information - oc get routes - $ oc get routes NAME HOST/PORT PATH SERVICES PORT TERMINATION MY_APP_NAME MY_APP_NAME-MY_PROJECT_NAME.OPENSHIFT_HOSTNAME MY_APP_NAME 8080- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - The route information of a pod gives you the base URL which you use to access it. In the example above, you would use - http://MY_APP_NAME-MY_PROJECT_NAME.OPENSHIFT_HOSTNAMEas the base URL to access the application.
5.3.3. Deploying the Relational Database Backend example application to Minishift or CDK
Use one of the following options to execute the Relational Database Backend example application locally on Minishift or CDK:
					Although each method uses the same oc commands to deploy your application, using Fabric8 Launcher provides an automated deployment workflow that executes the oc commands for you.
				
5.3.3.1. Getting the Fabric8 Launcher tool URL and credentials
You need the Fabric8 Launcher tool URL and user credentials to create and deploy example applications on Minishift or CDK. This information is provided when the Minishift or CDK is started.
Prerequisites
- The Fabric8 Launcher tool installed, configured, and running.
Procedure
- Navigate to the console where you started Minishift or CDK.
- Check the console output for the URL and user credentials you can use to access the running Fabric8 Launcher: - Example Console Output from a Minishift or CDK Startup - Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
5.3.3.2. Deploying the example application using the Fabric8 Launcher tool
This section shows you how to build your REST API Level 0 example application and deploy it to OpenShift from the Fabric8 Launcher web interface.
Prerequisites
- The URL of your running Fabric8 Launcher instance and the user credentials of your Minishift or CDK. For more information, see Section 5.3.3.1, “Getting the Fabric8 Launcher tool URL and credentials”.
Procedure
- Navigate to the Fabric8 Launcher URL in a browser.
- Follow the on-screen instructions to create and launch your example application in Node.js.
5.3.3.3. Authenticating the oc CLI client
						To work with example applications on Minishift or CDK using the oc command-line client, you must authenticate the client using the token provided by the Minishift or CDK web interface.
					
Prerequisites
- The URL of your running Fabric8 Launcher instance and the user credentials of your Minishift or CDK. For more information, see Section 5.3.3.1, “Getting the Fabric8 Launcher tool URL and credentials”.
Procedure
- Navigate to the Minishift or CDK URL in a browser.
- Click on the question mark icon in the top right-hand corner of the Web console, next to your user name.
- Select Command Line Tools in the drop-down menu.
- 
								Copy the oc logincommand.
- Paste the command in a terminal. The command uses your authentication token to authenticate your - ocCLI client with your Minishift or CDK account.- oc login OPENSHIFT_URL --token=MYTOKEN - $ oc login OPENSHIFT_URL --token=MYTOKEN- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
5.3.3.4. Deploying the Relational Database Backend example application using the oc CLI client
This section shows you how to build your Relational Database Backend example application and deploy it to OpenShift from the command line.
Prerequisites
- The example application created using Fabric8 Launcher tool on a Minishift or CDK. For more information, see Section 5.3.3.2, “Deploying the example application using the Fabric8 Launcher tool”.
- Your Fabric8 Launcher tool URL.
- 
								The occlient authenticated. For more information, see Section 5.3.3.3, “Authenticating theocCLI client”.
Procedure
- Clone your project from GitHub. - git clone git@github.com:USERNAME/MY_PROJECT_NAME.git - $ git clone git@github.com:USERNAME/MY_PROJECT_NAME.git- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - Alternatively, if you downloaded a ZIP file of your project, extract it. - unzip MY_PROJECT_NAME.zip - $ unzip MY_PROJECT_NAME.zip- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
- Create a new OpenShift project. - oc new-project MY_PROJECT_NAME - $ oc new-project MY_PROJECT_NAME- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
- Navigate to the root directory of your application.
- Deploy the PostgreSQL database to OpenShift. Ensure that you use the following values for user name, password, and database name when creating your database application. The example application is pre-configured to use these values. Using different values prevents your application from integrating with the database. - oc new-app -e POSTGRESQL_USER=luke -ePOSTGRESQL_PASSWORD=secret -ePOSTGRESQL_DATABASE=my_data registry.access.redhat.com/rhscl/postgresql-10-rhel7 --name=my-database - $ oc new-app -e POSTGRESQL_USER=luke -ePOSTGRESQL_PASSWORD=secret -ePOSTGRESQL_DATABASE=my_data registry.access.redhat.com/rhscl/postgresql-10-rhel7 --name=my-database- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
- Check the status of your database and ensure the pod is running. - oc get pods -w - $ oc get pods -w my-database-1-aaaaa 1/1 Running 0 45s my-database-1-deploy 0/1 Completed 0 53s- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - The - my-database-1-aaaaapod should have a status of- Runningand should be indicated as ready once it is fully deployed and started. Your specific pod name will vary. The number in the middle will increase with each new build. The letters at the end are generated when the pod is created.
- Use - npmto start the deployment to OpenShift.- npm install && npm run openshift - $ npm install && npm run openshift- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - These commands install any missing module dependencies, then using the Nodeshift module, deploy the example application on OpenShift. 
- Check the status of your application and ensure your pod is running. - oc get pods -w - $ oc get pods -w NAME READY STATUS RESTARTS AGE MY_APP_NAME-1-aaaaa 1/1 Running 0 58s MY_APP_NAME-s2i-1-build 0/1 Completed 0 2m- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - Your - MY_APP_NAME-1-aaaaapod should have a status of- Runningand should be indicated as ready once it is fully deployed and started.
- After your example application is deployed and started, determine its route. - Example Route Information - oc get routes - $ oc get routes NAME HOST/PORT PATH SERVICES PORT TERMINATION MY_APP_NAME MY_APP_NAME-MY_PROJECT_NAME.OPENSHIFT_HOSTNAME MY_APP_NAME 8080- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - The route information of a pod gives you the base URL which you use to access it. In the example above, you would use - http://MY_APP_NAME-MY_PROJECT_NAME.OPENSHIFT_HOSTNAMEas the base URL to access the application.
5.3.4. Deploying the Relational Database Backend example application to OpenShift Container Platform
The process of creating and deploying example applications to OpenShift Container Platform is similar to OpenShift Online:
Prerequisites
- The example application created using developers.redhat.com/launch.
Procedure
- Follow the instructions in Section 5.3.2, “Deploying the Relational Database Backend example application to OpenShift Online”, only use the URL and user credentials from the OpenShift Container Platform Web Console.
5.3.5. Interacting with the Relational Database Backend API on Node.js
When you have finished creating your example application, you can interact with it the following way:
Prerequisites
- Your application running
- 
							The curlbinary or a web browser
Procedure
- Obtain the URL of your application by executing the following command: - oc get route MY_APP_NAME - $ oc get route MY_APP_NAME- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - NAME HOST/PORT PATH SERVICES PORT TERMINATION MY_APP_NAME MY_APP_NAME-MY_PROJECT_NAME.OPENSHIFT_HOSTNAME MY_APP_NAME 8080 - NAME HOST/PORT PATH SERVICES PORT TERMINATION MY_APP_NAME MY_APP_NAME-MY_PROJECT_NAME.OPENSHIFT_HOSTNAME MY_APP_NAME 8080- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
- To access the web interface of the database application, navigate to the application URL in your browser: - http://MY_APP_NAME-MY_PROJECT_NAME.OPENSHIFT_HOSTNAME - http://MY_APP_NAME-MY_PROJECT_NAME.OPENSHIFT_HOSTNAME- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - Alternatively, you can make requests directly on the - api/fruits/*endpoint using- curl:- List all entries in the database: - curl http://MY_APP_NAME-MY_PROJECT_NAME.OPENSHIFT_HOSTNAME/api/fruits - $ curl http://MY_APP_NAME-MY_PROJECT_NAME.OPENSHIFT_HOSTNAME/api/fruits- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - Retrieve an entry with a specific ID - curl http://MY_APP_NAME-MY_PROJECT_NAME.OPENSHIFT_HOSTNAME/api/fruits/3 - $ curl http://MY_APP_NAME-MY_PROJECT_NAME.OPENSHIFT_HOSTNAME/api/fruits/3- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - { "id" : 3, "name" : "Pear", "stock" : 10 }- { "id" : 3, "name" : "Pear", "stock" : 10 }- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - Create a new entry: - curl -H "Content-Type: application/json" -X POST -d '{"name":"Peach","stock":1}' http://MY_APP_NAME-MY_PROJECT_NAME.OPENSHIFT_HOSTNAME/api/fruits- $ curl -H "Content-Type: application/json" -X POST -d '{"name":"Peach","stock":1}' http://MY_APP_NAME-MY_PROJECT_NAME.OPENSHIFT_HOSTNAME/api/fruits- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - { "id" : 4, "name" : "Peach", "stock" : 1 }- { "id" : 4, "name" : "Peach", "stock" : 1 }- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - Update an Entry - curl -H "Content-Type: application/json" -X PUT -d '{"name":"Apple","stock":100}' http://MY_APP_NAME-MY_PROJECT_NAME.OPENSHIFT_HOSTNAME/api/fruits/1- $ curl -H "Content-Type: application/json" -X PUT -d '{"name":"Apple","stock":100}' http://MY_APP_NAME-MY_PROJECT_NAME.OPENSHIFT_HOSTNAME/api/fruits/1- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - { "id" : 1, "name" : "Apple", "stock" : 100 }- { "id" : 1, "name" : "Apple", "stock" : 100 }- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - Delete an Entry: - curl -X DELETE http://MY_APP_NAME-MY_PROJECT_NAME.OPENSHIFT_HOSTNAME/api/fruits/1 - $ curl -X DELETE http://MY_APP_NAME-MY_PROJECT_NAME.OPENSHIFT_HOSTNAME/api/fruits/1- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
Troubleshooting
- 
							If you receive an HTTP Error code 503as a response after executing these commands, it means that the application is not ready yet.
5.3.6. Relational database resources
More background and related information on running relational databases in OpenShift, CRUD, HTTP API and REST can be found here:
- HTTP Verbs
- Architectural Styles and the Design of Network-based Software Architectures - Representational State Transfer (REST)
- The never ending REST API design debase
- REST APIs must be Hypertext driven
- Richardson Maturity Model
- Express Web Framework
- Relational Database Backend for Spring Boot
- Relational Database Backend for Eclipse Vert.x
- Relational Database Backend for Thorntail
5.4. Health Check example for Node.js
The following example is not meant to be run in a production environment.
Example proficiency level: Foundational.
When you deploy an application, it is important to know if it is available and if it can start handling incoming requests. Implementing the health check pattern allows you to monitor the health of an application, which includes if an application is available and whether it is able to service requests.
If you are not familiar with the health check terminology, see the Section 5.4.1, “Health check concepts” section first.
				The purpose of this use case is to demonstrate the health check pattern through the use of probing. Probing is used to report the liveness and readiness of an application. In this use case, you configure an application which exposes an HTTP health endpoint to issue HTTP requests. If the container is alive, according to the liveness probe on the health HTTP endpoint, the management platform receives 200 as return code and no further action is required. If the health HTTP endpoint does not return a response, for example if the thread is blocked, then the application is not considered alive according to the liveness probe. In that case, the platform kills the pod corresponding to that application and recreates a new pod to restart the application.
			
				This use case also allows you to demonstrate and use a readiness probe. In cases where the application is running but is unable to handle requests, such as when the application returns an HTTP 503 response code during restart, this application is not considered ready according to the readiness probe. If the application is not considered ready by the readiness probe, requests are not routed to that application until it is considered ready according to the readiness probe.
			
5.4.1. Health check concepts
In order to understand the health check pattern, you need to first understand the following concepts:
- Liveness
- Liveness defines whether an application is running or not. Sometimes a running application moves into an unresponsive or stopped state and needs to be restarted. Checking for liveness helps determine whether or not an application needs to be restarted.
- Readiness
- Readiness defines whether a running application can service requests. Sometimes a running application moves into an error or broken state where it can no longer service requests. Checking readiness helps determine whether or not requests should continue to be routed to that application.
- Fail-over
- Fail-over enables failures in servicing requests to be handled gracefully. If an application fails to service a request, that request and future requests can then fail-over or be routed to another application, which is usually a redundant copy of that same application.
- Resilience and Stability
- Resilience and Stability enable failures in servicing requests to be handled gracefully. If an application fails to service a request due to connection loss, in a resilient system that request can be retried after the connection is re-established.
- Probe
- A probe is a Kubernetes action that periodically performs diagnostics on a running container.
5.4.2. Deploying the Health Check example application to OpenShift Online
Use one of the following options to execute the Health Check example application on OpenShift Online.
					Although each method uses the same oc commands to deploy your application, using developers.redhat.com/launch provides an automated deployment workflow that executes the oc commands for you.
				
5.4.2.1. Deploying the example application using developers.redhat.com/launch
This section shows you how to build your REST API Level 0 example application and deploy it to OpenShift from the Red Hat Developer Launcher web interface.
Prerequisites
- An account at OpenShift Online.
Procedure
- Navigate to the developers.redhat.com/launch URL in a browser.
- Follow on-screen instructions to create and launch your example application in Node.js.
5.4.2.2. Authenticating the oc CLI client
						To work with example applications on OpenShift Online using the oc command-line client, you must authenticate the client using the token provided by the OpenShift Online web interface.
					
Prerequisites
- An account at OpenShift Online.
Procedure
- Navigate to the OpenShift Online URL in a browser.
- Click on the question mark icon in the top right-hand corner of the Web console, next to your user name.
- Select Command Line Tools in the drop-down menu.
- 
								Copy the oc logincommand.
- Paste the command in a terminal. The command uses your authentication token to authenticate your - ocCLI client with your OpenShift Online account.- oc login OPENSHIFT_URL --token=MYTOKEN - $ oc login OPENSHIFT_URL --token=MYTOKEN- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
5.4.2.3. Deploying the Health Check example application using the oc CLI client
This section shows you how to build your Health Check example application and deploy it to OpenShift from the command line.
Prerequisites
- The example application created using developers.redhat.com/launch. For more information, see Section 5.4.2.1, “Deploying the example application using developers.redhat.com/launch”.
- 
								The occlient authenticated. For more information, see Section 5.4.2.2, “Authenticating theocCLI client”.
Procedure
- Clone your project from GitHub. - git clone git@github.com:USERNAME/MY_PROJECT_NAME.git - $ git clone git@github.com:USERNAME/MY_PROJECT_NAME.git- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - Alternatively, if you downloaded a ZIP file of your project, extract it. - unzip MY_PROJECT_NAME.zip - $ unzip MY_PROJECT_NAME.zip- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
- Create a new OpenShift project. - oc new-project MY_PROJECT_NAME - $ oc new-project MY_PROJECT_NAME- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
- Navigate to the root directory of your application.
- Use - npmto start the deployment to OpenShift.- npm install && npm run openshift - $ npm install && npm run openshift- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - These commands install any missing module dependencies, then using the Nodeshift module, deploy the example application on OpenShift. 
- Check the status of your application and ensure your pod is running. - oc get pods -w - $ oc get pods -w NAME READY STATUS RESTARTS AGE MY_APP_NAME-1-aaaaa 1/1 Running 0 58s MY_APP_NAME-s2i-1-build 0/1 Completed 0 2m- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - The - MY_APP_NAME-1-aaaaapod should have a status of- Runningonce its fully deployed and started. You should also wait for your pod to be ready before proceeding, which is shown in the- READYcolumn. For example,- MY_APP_NAME-1-aaaaais ready when the- READYcolumn is- 1/1. Your specific pod name will vary. The number in the middle will increase with each new build. The letters at the end are generated when the pod is created.
- After your example application is deployed and started, determine its route. - Example Route Information - oc get routes - $ oc get routes NAME HOST/PORT PATH SERVICES PORT TERMINATION MY_APP_NAME MY_APP_NAME-MY_PROJECT_NAME.OPENSHIFT_HOSTNAME MY_APP_NAME 8080- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - The route information of a pod gives you the base URL which you use to access it. In the example above, you would use - http://MY_APP_NAME-MY_PROJECT_NAME.OPENSHIFT_HOSTNAMEas the base URL to access the application.
5.4.3. Deploying the Health Check example application to Minishift or CDK
Use one of the following options to execute the Health Check example application locally on Minishift or CDK:
					Although each method uses the same oc commands to deploy your application, using Fabric8 Launcher provides an automated deployment workflow that executes the oc commands for you.
				
5.4.3.1. Getting the Fabric8 Launcher tool URL and credentials
You need the Fabric8 Launcher tool URL and user credentials to create and deploy example applications on Minishift or CDK. This information is provided when the Minishift or CDK is started.
Prerequisites
- The Fabric8 Launcher tool installed, configured, and running.
Procedure
- Navigate to the console where you started Minishift or CDK.
- Check the console output for the URL and user credentials you can use to access the running Fabric8 Launcher: - Example Console Output from a Minishift or CDK Startup - Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
5.4.3.2. Deploying the example application using the Fabric8 Launcher tool
This section shows you how to build your REST API Level 0 example application and deploy it to OpenShift from the Fabric8 Launcher web interface.
Prerequisites
- The URL of your running Fabric8 Launcher instance and the user credentials of your Minishift or CDK. For more information, see Section 5.4.3.1, “Getting the Fabric8 Launcher tool URL and credentials”.
Procedure
- Navigate to the Fabric8 Launcher URL in a browser.
- Follow the on-screen instructions to create and launch your example application in Node.js.
5.4.3.3. Authenticating the oc CLI client
						To work with example applications on Minishift or CDK using the oc command-line client, you must authenticate the client using the token provided by the Minishift or CDK web interface.
					
Prerequisites
- The URL of your running Fabric8 Launcher instance and the user credentials of your Minishift or CDK. For more information, see Section 5.4.3.1, “Getting the Fabric8 Launcher tool URL and credentials”.
Procedure
- Navigate to the Minishift or CDK URL in a browser.
- Click on the question mark icon in the top right-hand corner of the Web console, next to your user name.
- Select Command Line Tools in the drop-down menu.
- 
								Copy the oc logincommand.
- Paste the command in a terminal. The command uses your authentication token to authenticate your - ocCLI client with your Minishift or CDK account.- oc login OPENSHIFT_URL --token=MYTOKEN - $ oc login OPENSHIFT_URL --token=MYTOKEN- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
5.4.3.4. Deploying the Health Check example application using the oc CLI client
This section shows you how to build your Health Check example application and deploy it to OpenShift from the command line.
Prerequisites
- The example application created using Fabric8 Launcher tool on a Minishift or CDK. For more information, see Section 5.4.3.2, “Deploying the example application using the Fabric8 Launcher tool”.
- Your Fabric8 Launcher tool URL.
- 
								The occlient authenticated. For more information, see Section 5.4.3.3, “Authenticating theocCLI client”.
Procedure
- Clone your project from GitHub. - git clone git@github.com:USERNAME/MY_PROJECT_NAME.git - $ git clone git@github.com:USERNAME/MY_PROJECT_NAME.git- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - Alternatively, if you downloaded a ZIP file of your project, extract it. - unzip MY_PROJECT_NAME.zip - $ unzip MY_PROJECT_NAME.zip- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
- Create a new OpenShift project. - oc new-project MY_PROJECT_NAME - $ oc new-project MY_PROJECT_NAME- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
- Navigate to the root directory of your application.
- Use - npmto start the deployment to OpenShift.- npm install && npm run openshift - $ npm install && npm run openshift- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - These commands install any missing module dependencies, then using the Nodeshift module, deploy the example application on OpenShift. 
- Check the status of your application and ensure your pod is running. - oc get pods -w - $ oc get pods -w NAME READY STATUS RESTARTS AGE MY_APP_NAME-1-aaaaa 1/1 Running 0 58s MY_APP_NAME-s2i-1-build 0/1 Completed 0 2m- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - The - MY_APP_NAME-1-aaaaapod should have a status of- Runningonce its fully deployed and started. You should also wait for your pod to be ready before proceeding, which is shown in the- READYcolumn. For example,- MY_APP_NAME-1-aaaaais ready when the- READYcolumn is- 1/1. Your specific pod name will vary. The number in the middle will increase with each new build. The letters at the end are generated when the pod is created.
- After your example application is deployed and started, determine its route. - Example Route Information - oc get routes - $ oc get routes NAME HOST/PORT PATH SERVICES PORT TERMINATION MY_APP_NAME MY_APP_NAME-MY_PROJECT_NAME.OPENSHIFT_HOSTNAME MY_APP_NAME 8080- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - The route information of a pod gives you the base URL which you use to access it. In the example above, you would use - http://MY_APP_NAME-MY_PROJECT_NAME.OPENSHIFT_HOSTNAMEas the base URL to access the application.
5.4.4. Deploying the Health Check example application to OpenShift Container Platform
The process of creating and deploying example applications to OpenShift Container Platform is similar to OpenShift Online:
Prerequisites
- The example application created using developers.redhat.com/launch.
Procedure
- Follow the instructions in Section 5.4.2, “Deploying the Health Check example application to OpenShift Online”, only use the URL and user credentials from the OpenShift Container Platform Web Console.
5.4.5. Interacting with the unmodified Health Check example application
					After you deploy the example application, you will have the MY_APP_NAME service running. The MY_APP_NAME service exposes the following REST endpoints:
				
- /api/greeting
- 
								Returns a JSON containing greeting of nameparameter (or World as default value).
- /api/stop
- Forces the service to become unresponsive as means to simulate a failure.
The following steps demonstrate how to verify the service availability and simulate a failure. This failure of an available service causes the OpenShift self-healing capabilities to be trigger on the service.
Alternatively, you can use the web interface to perform these steps.
- Use - curlto execute a- GETrequest against the- MY_APP_NAMEservice. You can also use a browser to do this.- curl http://MY_APP_NAME-MY_PROJECT_NAME.OPENSHIFT_HOSTNAME/api/greeting - $ curl http://MY_APP_NAME-MY_PROJECT_NAME.OPENSHIFT_HOSTNAME/api/greeting- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - {"content":"Hello, World!"}- {"content":"Hello, World!"}- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
- Invoke the - /api/stopendpoint and verify the availability of the- /api/greetingendpoint shortly after that.- Invoking the - /api/stopendpoint simulates an internal service failure and triggers the OpenShift self-healing capabilities. When invoking- /api/greetingafter simulating the failure, the service should return a HTTP status- 503.- curl http://MY_APP_NAME-MY_PROJECT_NAME.OPENSHIFT_HOSTNAME/api/stop - $ curl http://MY_APP_NAME-MY_PROJECT_NAME.OPENSHIFT_HOSTNAME/api/stop- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - Stopping HTTP server, Bye bye world ! - Stopping HTTP server, Bye bye world !- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - (followed by) - curl http://MY_APP_NAME-MY_PROJECT_NAME.OPENSHIFT_HOSTNAME/api/greeting - $ curl http://MY_APP_NAME-MY_PROJECT_NAME.OPENSHIFT_HOSTNAME/api/greeting- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - Not online - Not online- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
- Use - oc get pods -wto continuously watch the self-healing capabilities in action.- While invoking the service failure, you can watch the self-healing capabilities in action on OpenShift console, or with the - occlient tools. You should see the number of pods in the- READYstate move to zero (- 0/1) and after a short period (less than one minute) move back up to one (- 1/1). In addition to that, the- RESTARTScount increases every time you you invoke the service failure.- oc get pods -w - $ oc get pods -w NAME READY STATUS RESTARTS AGE MY_APP_NAME-1-26iy7 0/1 Running 5 18m MY_APP_NAME-1-26iy7 1/1 Running 5 19m- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
- Optional: Use the web interface to invoke the service. - Alternatively to the interaction using the terminal window, you can use the web interface provided by the service to invoke the different methods and watch the service move through the life cycle phases. - http://MY_APP_NAME-MY_PROJECT_NAME.OPENSHIFT_HOSTNAME - http://MY_APP_NAME-MY_PROJECT_NAME.OPENSHIFT_HOSTNAME- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
- Optional: Use the web console to view the log output generated by the application at each stage of the self-healing process. - Navigate to your project.
- On the sidebar, click on Monitoring.
- In the upper right-hand corner of the screen, click on Events to display the log messages.
- Optional: Click View Details to display a detailed view of the Event log.
 - The health check application generates the following messages: - Expand - Message - Status - Unhealthy - Readiness probe failed. This message is expected and indicates that the simulated failure of the - /api/greetingendpoint has been detected and the self-healing process starts.- Killing - The unavailable Docker container running the service is being killed before being re-created. - Pulling - Downloading the latest version of docker image to re-create the container. - Pulled - Docker image downloaded successfully. - Created - Docker container has been successfully created - Started - Docker container is ready to handle requests 
5.4.6. Health check resources
More background and related information on health checking can be found here:
5.5. Circuit Breaker example for Node.js
The following example is not meant to be run in a production environment.
Limitation: Run this example application on a Minishift or CDK. You can also use a manual workflow to deploy this example to OpenShift Online Pro and OpenShift Container Platform. This example is not currently available on OpenShift Online Starter.
Example proficiency level: Foundational.
The Circuit Breaker example demonstrates a generic pattern for reporting the failure of a service and then limiting access to the failed service until it becomes available to handle requests. This helps prevent cascading failure in other services that depend on the failed services for functionality.
This example shows you how to implement a Circuit Breaker and Fallback pattern in your services.
5.5.1. The circuit breaker design pattern
The Circuit Breaker is a pattern intended to:
- Reduce the impact of network failure and high latency on service architectures where services synchronously invoke other services. - If one of the services: - becomes unavailable due to network failure, or
- incurs unusually high latency values due to overwhelming traffic,
 - other services attempting to call its endpoint may end up exhausting critical resources in an attempt to reach it, rendering themselves unusable. 
- Prevent the condition also known as cascading failure, which can render the entire microservice architecture unusable.
- Act as a proxy between a protected function and a remote function, which monitors for failures.
- Trip once the failures reach a certain threshold, and all further calls to the circuit breaker return an error or a predefined fallback response, without the protected call being made at all.
The Circuit Breaker usually also contain an error reporting mechanism that notifies you when the Circuit Breaker trips.
Circuit breaker implementation
- With the Circuit Breaker pattern implemented, a service client invokes a remote service endpoint via a proxy at regular intervals.
- If the calls to the remote service endpoint fail repeatedly and consistently, the Circuit Breaker trips, making all calls to the service fail immediately over a set timeout period and returns a predefined fallback response.
- When the timeout period expires, a limited number of test calls are allowed to pass through to the remote service to determine whether it has healed, or remains unavailable. - If the test calls fail, the Circuit Breaker keeps the service unavailable and keeps returning the fallback responses to incoming calls.
- If the test calls succeed, the Circuit Breaker closes, fully enabling traffic to reach the remote service again.
 
5.5.2. Circuit Breaker design tradeoffs
| Pros | Cons | 
|---|---|
| 
 | 
 | 
5.5.3. Circuit breaker add-on for Red Hat build of Node.js
Red Hat provides a circuit breaker add-on for Red Hat build of Node.js, which is a fully supported implementation of the open source Opossum module. You can download and install the circuit breaker add-on from the Red Hat customer registry. You can use the circuit breaker add-on in your Node.js applications to ensure that application failures are monitored and handled appropriately. When using the circuit breaker add-on, you can also define a fallback function to perform a specified action whenever an application failure occurs. You can also define event handlers to listen for different types of circuit breaker events.
5.5.4. Deploying the Circuit Breaker example application to OpenShift Online
Use one of the following options to execute the Circuit Breaker example application on OpenShift Online.
					Although each method uses the same oc commands to deploy your application, using developers.redhat.com/launch provides an automated deployment workflow that executes the oc commands for you.
				
5.5.4.1. Deploying the example application using developers.redhat.com/launch
This section shows you how to build your REST API Level 0 example application and deploy it to OpenShift from the Red Hat Developer Launcher web interface.
Prerequisites
- An account at OpenShift Online.
Procedure
- Navigate to the developers.redhat.com/launch URL in a browser.
- Follow on-screen instructions to create and launch your example application in Node.js.
5.5.4.2. Authenticating the oc CLI client
						To work with example applications on OpenShift Online using the oc command-line client, you must authenticate the client using the token provided by the OpenShift Online web interface.
					
Prerequisites
- An account at OpenShift Online.
Procedure
- Navigate to the OpenShift Online URL in a browser.
- Click on the question mark icon in the top right-hand corner of the Web console, next to your user name.
- Select Command Line Tools in the drop-down menu.
- 
								Copy the oc logincommand.
- Paste the command in a terminal. The command uses your authentication token to authenticate your - ocCLI client with your OpenShift Online account.- oc login OPENSHIFT_URL --token=MYTOKEN - $ oc login OPENSHIFT_URL --token=MYTOKEN- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
5.5.4.3. Deploying the Circuit Breaker example application using the oc CLI client
This section shows you how to build your Circuit Breaker example application and deploy it to OpenShift from the command line.
Prerequisites
- The example application created using developers.redhat.com/launch. For more information, see Section 5.5.4.1, “Deploying the example application using developers.redhat.com/launch”.
- 
								The occlient authenticated. For more information, see Section 5.5.4.2, “Authenticating theocCLI client”.
Procedure
- Clone your project from GitHub. - git clone git@github.com:USERNAME/MY_PROJECT_NAME.git - $ git clone git@github.com:USERNAME/MY_PROJECT_NAME.git- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - Alternatively, if you downloaded a ZIP file of your project, extract it. - unzip MY_PROJECT_NAME.zip - $ unzip MY_PROJECT_NAME.zip- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
- Create a new OpenShift project. - oc new-project MY_PROJECT_NAME - $ oc new-project MY_PROJECT_NAME- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
- Navigate to the root directory of your application.
- Use the provided - start-openshift.shscript to start the deployment to OpenShift.- chmod +x start-openshift.sh ./start-openshift.sh - $ chmod +x start-openshift.sh $ ./start-openshift.sh- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - These commands use the Nodeshift - npmmodule to install your dependencies, launch the S2I build process on OpenShift, and start the services.
- Check the status of your application and ensure your pod is running. - Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - Both the - MY_APP_NAME-greeting-1-aaaaaand- MY_APP_NAME-name-1-aaaaapods should have a status of- Runningonce they are fully deployed and started. You should also wait for your pods to be ready before proceeding, which is shown in the- READYcolumn. For example,- MY_APP_NAME-greeting-1-aaaaais ready when the- READYcolumn is- 1/1. Your specific pod names will vary. The number in the middle will increase with each new build. The letters at the end are generated when the pod is created.
- After your example application is deployed and started, determine its route. - Example Route Information - oc get routes - $ oc get routes NAME HOST/PORT PATH SERVICES PORT TERMINATION MY_APP_NAME-greeting MY_APP_NAME-greeting-MY_PROJECT_NAME.OPENSHIFT_HOSTNAME MY_APP_NAME-greeting 8080 None MY_APP_NAME-name MY_APP_NAME-name-MY_PROJECT_NAME.OPENSHIFT_HOSTNAME MY_APP_NAME-name 8080 None- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - The route information of a pod gives you the base URL which you use to access it. In the example above, you would use - http://MY_APP_NAME-greeting-MY_PROJECT_NAME.OPENSHIFT_HOSTNAMEas the base URL to access the application.
5.5.5. Deploying the Circuit Breaker example application to Minishift or CDK
Use one of the following options to execute the Circuit Breaker example application locally on Minishift or CDK:
					Although each method uses the same oc commands to deploy your application, using Fabric8 Launcher provides an automated deployment workflow that executes the oc commands for you.
				
5.5.5.1. Getting the Fabric8 Launcher tool URL and credentials
You need the Fabric8 Launcher tool URL and user credentials to create and deploy example applications on Minishift or CDK. This information is provided when the Minishift or CDK is started.
Prerequisites
- The Fabric8 Launcher tool installed, configured, and running.
Procedure
- Navigate to the console where you started Minishift or CDK.
- Check the console output for the URL and user credentials you can use to access the running Fabric8 Launcher: - Example Console Output from a Minishift or CDK Startup - Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
5.5.5.2. Deploying the example application using the Fabric8 Launcher tool
This section shows you how to build your REST API Level 0 example application and deploy it to OpenShift from the Fabric8 Launcher web interface.
Prerequisites
- The URL of your running Fabric8 Launcher instance and the user credentials of your Minishift or CDK. For more information, see Section 5.5.5.1, “Getting the Fabric8 Launcher tool URL and credentials”.
Procedure
- Navigate to the Fabric8 Launcher URL in a browser.
- Follow the on-screen instructions to create and launch your example application in Node.js.
5.5.5.3. Authenticating the oc CLI client
						To work with example applications on Minishift or CDK using the oc command-line client, you must authenticate the client using the token provided by the Minishift or CDK web interface.
					
Prerequisites
- The URL of your running Fabric8 Launcher instance and the user credentials of your Minishift or CDK. For more information, see Section 5.5.5.1, “Getting the Fabric8 Launcher tool URL and credentials”.
Procedure
- Navigate to the Minishift or CDK URL in a browser.
- Click on the question mark icon in the top right-hand corner of the Web console, next to your user name.
- Select Command Line Tools in the drop-down menu.
- 
								Copy the oc logincommand.
- Paste the command in a terminal. The command uses your authentication token to authenticate your - ocCLI client with your Minishift or CDK account.- oc login OPENSHIFT_URL --token=MYTOKEN - $ oc login OPENSHIFT_URL --token=MYTOKEN- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
5.5.5.4. Deploying the Circuit Breaker example application using the oc CLI client
This section shows you how to build your Circuit Breaker example application and deploy it to OpenShift from the command line.
Prerequisites
- The example application created using Fabric8 Launcher tool on a Minishift or CDK. For more information, see Section 5.5.5.2, “Deploying the example application using the Fabric8 Launcher tool”.
- Your Fabric8 Launcher tool URL.
- 
								The occlient authenticated. For more information, see Section 5.5.5.3, “Authenticating theocCLI client”.
Procedure
- Clone your project from GitHub. - git clone git@github.com:USERNAME/MY_PROJECT_NAME.git - $ git clone git@github.com:USERNAME/MY_PROJECT_NAME.git- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - Alternatively, if you downloaded a ZIP file of your project, extract it. - unzip MY_PROJECT_NAME.zip - $ unzip MY_PROJECT_NAME.zip- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
- Create a new OpenShift project. - oc new-project MY_PROJECT_NAME - $ oc new-project MY_PROJECT_NAME- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
- Navigate to the root directory of your application.
- Use the provided - start-openshift.shscript to start the deployment to OpenShift.- chmod +x start-openshift.sh ./start-openshift.sh - $ chmod +x start-openshift.sh $ ./start-openshift.sh- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - These commands use the Nodeshift - npmmodule to install your dependencies, launch the S2I build process on OpenShift, and start the services.
- Check the status of your application and ensure your pod is running. - Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - Both the - MY_APP_NAME-greeting-1-aaaaaand- MY_APP_NAME-name-1-aaaaapods should have a status of- Runningonce they are fully deployed and started. You should also wait for your pods to be ready before proceeding, which is shown in the- READYcolumn. For example,- MY_APP_NAME-greeting-1-aaaaais ready when the- READYcolumn is- 1/1. Your specific pod names will vary. The number in the middle will increase with each new build. The letters at the end are generated when the pod is created.
- After your example application is deployed and started, determine its route. - Example Route Information - oc get routes - $ oc get routes NAME HOST/PORT PATH SERVICES PORT TERMINATION MY_APP_NAME-greeting MY_APP_NAME-greeting-MY_PROJECT_NAME.OPENSHIFT_HOSTNAME MY_APP_NAME-greeting 8080 None MY_APP_NAME-name MY_APP_NAME-name-MY_PROJECT_NAME.OPENSHIFT_HOSTNAME MY_APP_NAME-name 8080 None- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - The route information of a pod gives you the base URL which you use to access it. In the example above, you would use - http://MY_APP_NAME-greeting-MY_PROJECT_NAME.OPENSHIFT_HOSTNAMEas the base URL to access the application.
5.5.6. Deploying the Circuit Breaker example application to OpenShift Container Platform
The process of creating and deploying example applications to OpenShift Container Platform is similar to OpenShift Online:
Prerequisites
- The example application created using developers.redhat.com/launch.
Procedure
- Follow the instructions in Section 5.5.4, “Deploying the Circuit Breaker example application to OpenShift Online”, only use the URL and user credentials from the OpenShift Container Platform Web Console.
5.5.7. Interacting with the unmodified Node.js Circuit Breaker example application
After you have the Node.js example application deployed, you have the following services running:
- MY_APP_NAME-name
- Exposes the following endpoints: - 
										the /api/nameendpoint, which returns a name when this service is working, and an error when this service is set up to demonstrate failure.
- 
										the /api/stateendpoint, which controls the behavior of the/api/nameendpoint and determines whether the service works correctly or demonstrates failure.
 
- 
										the 
- MY_APP_NAME-greeting
- Exposes the following endpoints: - the - /api/greetingendpoint that you can call to get a personalized greeting response.- When you call the - /api/greetingendpoint, it issues a call against the- /api/nameendpoint of the- MY_APP_NAME-nameservice as part of processing your request. The call made against the- /api/nameendpoint is protected by the Circuit Breaker.- If the remote endpoint is available, the - nameservice responds with an HTTP code- 200(- OK) and you receive the following greeting from the- /api/greetingendpoint:- {"content":"Hello, World!"}- {"content":"Hello, World!"}- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - If the remote endpoint is unavailable, the - nameservice responds with an HTTP code- 500(- Internal server error) and you receive a predefined fallback response from the- /api/greetingendpoint:- {"content":"Hello, Fallback!"}- {"content":"Hello, Fallback!"}- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
- the - /api/cb-stateendpoint, which returns the state of the Circuit Breaker. The state can be:- open : the circuit breaker is preventing requests from reaching the failed service,
- closed: the circuit breaker is allowing requests to reach the service.
 
 
The following steps demonstrate how to verify the availability of the service, simulate a failure and receive a fallback response.
- Use - curlto execute a- GETrequest against the- MY_APP_NAME-greetingservice. You can also use the- Invokebutton in the web interface to do this.- curl http://MY_APP_NAME-greeting-MY_PROJECT_NAME.LOCAL_OPENSHIFT_HOSTNAME/api/greeting - $ curl http://MY_APP_NAME-greeting-MY_PROJECT_NAME.LOCAL_OPENSHIFT_HOSTNAME/api/greeting {"content":"Hello, World!"}- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
- To simulate the failure of the - MY_APP_NAME-nameservice you can:- 
									use the Togglebutton in the web interface.
- 
									scale the number of replicas of the pod running the MY_APP_NAME-nameservice down to 0.
- execute an HTTP - PUTrequest against the- /api/stateendpoint of the- MY_APP_NAME-nameservice to set its state to- fail.- curl -X PUT -H "Content-Type: application/json" -d '{"state": "fail"}' http://MY_APP_NAME-name-MY_PROJECT_NAME.LOCAL_OPENSHIFT_HOSTNAME/api/state- $ curl -X PUT -H "Content-Type: application/json" -d '{"state": "fail"}' http://MY_APP_NAME-name-MY_PROJECT_NAME.LOCAL_OPENSHIFT_HOSTNAME/api/state- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
 
- 
									use the 
- Invoke the - /api/greetingendpoint. When several requests on the- /api/nameendpoint fail:- the Circuit Breaker opens,
- 
									the state indicator in the web interface changes from CLOSEDtoOPEN,
- the Circuit Breaker issues a fallback response when you invoke the - /api/greetingendpoint:- curl http://MY_APP_NAME-greeting-MY_PROJECT_NAME.LOCAL_OPENSHIFT_HOSTNAME/api/greeting - $ curl http://MY_APP_NAME-greeting-MY_PROJECT_NAME.LOCAL_OPENSHIFT_HOSTNAME/api/greeting {"content":"Hello, Fallback!"}- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
 
- Restore the name - MY_APP_NAME-nameservice to availability. To do this you can:- 
									use the Togglebutton in the web interface.
- 
									scale the number of replicas of the pod running the MY_APP_NAME-nameservice back up to 1.
- execute an HTTP - PUTrequest against the- /api/stateendpoint of the- MY_APP_NAME-nameservice to set its state back to- ok.- curl -X PUT -H "Content-Type: application/json" -d '{"state": "ok"}' http://MY_APP_NAME-name-MY_PROJECT_NAME.LOCAL_OPENSHIFT_HOSTNAME/api/state- $ curl -X PUT -H "Content-Type: application/json" -d '{"state": "ok"}' http://MY_APP_NAME-name-MY_PROJECT_NAME.LOCAL_OPENSHIFT_HOSTNAME/api/state- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
 
- 
									use the 
- Invoke the - /api/greetingendpoint again. When several requests on the- /api/nameendpoint succeed:- the Circuit Breaker closes,
- 
									the state indicator in the web interface changes from OPENtoCLOSED,
- the Circuit Breaker issues a returns the - Hello World!greeting when you invoke the- /api/greetingendpoint:- curl http://MY_APP_NAME-greeting-MY_PROJECT_NAME.LOCAL_OPENSHIFT_HOSTNAME/api/greeting - $ curl http://MY_APP_NAME-greeting-MY_PROJECT_NAME.LOCAL_OPENSHIFT_HOSTNAME/api/greeting {"content":"Hello, World!"}- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
 
5.5.8. Circuit breaker resources
Follow the links below for more background information on the design principles behind the Circuit Breaker pattern
5.6. Secured example application for Node.js
The following example is not meant to be run in a production environment.
Limitation: Run this example application on a Minishift or CDK. You can also use a manual workflow to deploy this example to OpenShift Online Pro and OpenShift Container Platform. This example is not currently available on OpenShift Online Starter.
Example proficiency level: Advanced.
The Secured example application secures a REST endpoint using Red Hat SSO. (This example expands on the REST API Level 0 example).
Red Hat SSO:
- Implements the Open ID Connect protocol which is an extension of the OAuth 2.0 specification.
- Issues access tokens to provide clients with various access rights to secured resources.
Securing an application with SSO enables you to add security to your applications while centralizing the security configuration.
This example comes with Red Hat SSO pre-configured for demonstration purposes, it does not explain its principles, usage, or configuration. Before using this example, ensure that you are familiar with the basic concepts related to Red Hat SSO.
5.6.1. The Secured project structure
The SSO example contains:
- the sources for the Greeting service, which is the one which we are going to to secure
- 
							a template file (service.sso.yaml) to deploy the SSO server
- the Keycloak adapter configuration to secure the service
5.6.2. Red Hat SSO deployment configuration
					The service.sso.yaml file in this example contains all OpenShift configuration items to deploy a pre-configured Red Hat SSO server. The SSO server configuration has been simplified for the sake of this exercise and does provide an out-of-the-box configuration, with pre-configured users and security settings. The service.sso.yaml file also contains very long lines, and some text editors, such as gedit, may have issues reading this file.
				
It is not recommended to use this SSO configuration in production. Specifically, the simplifications made to the example security configuration impact the ability to use it in a production environment.
| Change | Reason | Recommendation | 
|---|---|---|
| The default configuration includes both public and private keys in the yaml configuration files. | We did this because the end user can deploy Red Hat SSO module and have it in a usable state without needing to know the internals or how to configure Red Hat SSO. | In production, do not store private keys under source control. They should be added by the server administrator. | 
| The configured clients accept any callback url. | To avoid having a custom configuration for each runtime, we avoid the callback verification that is required by the OAuth2 specification. | An application-specific callback URL should be provided with a valid domain name. | 
| Clients do not require SSL/TLS and the secured applications are not exposed over HTTPS. | The examples are simplified by not requiring certificates generated for each runtime. | In production a secure application should use HTTPS rather than plain HTTP. | 
| The token timeout has been increased to 10 minutes from the default of 1 minute. | Provides a better user experience when working with the command line examples | From a security perspective, the window an attacker would have to guess the access token is extended. It is recommended to keep this window short as it makes it much harder for a potential attacker to guess the current token. | 
5.6.3. Red Hat SSO realm model
					The master realm is used to secure this example. There are two pre-configured application client definitions that provide a model for command line clients and the secured REST endpoint.
				
					There are also two pre-configured users in the Red Hat SSO master realm that can be used to validate various authentication and authorization outcomes: admin and alice.
				
5.6.3.1. Red Hat SSO users
The realm model for the secured examples includes two users:
- admin
- 
									The adminuser has a password ofadminand is the realm administrator. This user has full access to the Red Hat SSO administration console, but none of the role mappings that are required to access the secured endpoints. You can use this user to illustrate the behavior of an authenticated, but unauthorized user.
- alice
- The - aliceuser has a password of- passwordand is the canonical application user. This user will demonstrate successful authenticated and authorized access to the secured endpoints. An example representation of the role mappings is provided in this decoded JWT bearer token:- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - 1
- Theissfield corresponds to the Red Hat SSO realm instance URL that issues the token. This must be configured in the secured endpoint deployments in order for the token to be verified.
- 2
- Therolesobject provides the roles that have been granted to the user at the global realm level. In this casealicehas been granted theexample-adminrole. We will see that the secured endpoint will look to the realm level for authorized roles.
- 3
- Theresource_accessobject contains resource specific role grants. Under this object you will find an object for each of the secured endpoints.
- 4
- Theresource_access.secured-example-endpoint.rolesobject contains the roles granted toalicefor thesecured-example-endpointresource.
- 5
- Thepreferred_usernamefield provides the username that was used to generate the access token.
 
5.6.3.2. The application clients
						The OAuth 2.0 specification allows you to define a role for application clients that access secured resources on behalf of resource owners. The master realm has the following application clients defined:
					
- demoapp
- 
									This is a confidentialtype client with a client secret that is used to obtain an access token. The token contains grants for thealiceuser which enablealiceto access the Thorntail, Eclipse Vert.x, Node.js and Spring Boot based REST example application deployments.
- secured-example-endpoint
- 
									The secured-example-endpointis a bearer-only type of client that requires aexample-adminrole for accessing the associated resources, specifically the Greeting service.
5.6.4. Node.js SSO adapter configuration
The SSO adapter is the client side, or client to the SSO server, component that enforces security on the web resources. In this specific case, it is the Greeting service.
Enacting Security Example Node.js Code
- 1
- npmmodule keycloak-connect must be installed and- required. The keycloak-connect module acts as connect middleware, which provides integration with- express.
- 2
- Instantiate a newKeycloakobject and pass in an empty configuration object.
- 3
- Tellsexpressto use Keycloak as middleware.
- 4
- Enforces that a user must be authenticated and part of the example-admin role before accessing a resource.
Enacting Security in Keycloak Adapter using keycloak.json
- 1
- The security realm to be used.
- 2
- The actual Keycloak client configuration.
- 3
- PEM format of the realm public key. You can obtain this from the administration console.
- 4
- The address of the Red Hat SSO server (Interpolation at build time).
- 5
- If enabled the adapter will not attempt to authenticate users, but only verify bearer tokens.
					The example Node.js code enables Keycloak and enforces protection of the Greeting service web resource endpoint. The keycloak.json configures the security adapter to interact with Red Hat SSO.
				
Additional resources
- For more information about the Node.js Keycloak adapter, see the Keycloak documentation.
5.6.5. Deploying the Secured example application to Minishift or CDK
5.6.5.1. Getting the Fabric8 Launcher tool URL and credentials
You need the Fabric8 Launcher tool URL and user credentials to create and deploy example applications on Minishift or CDK. This information is provided when the Minishift or CDK is started.
Prerequisites
- The Fabric8 Launcher tool installed, configured, and running.
Procedure
- Navigate to the console where you started Minishift or CDK.
- Check the console output for the URL and user credentials you can use to access the running Fabric8 Launcher: - Example Console Output from a Minishift or CDK Startup - Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
5.6.5.2. Creating the Secured example application using Fabric8 Launcher
Prerequisites
- The URL and user credentials of your running Fabric8 Launcher instance. For more information, see Section 5.6.5.1, “Getting the Fabric8 Launcher tool URL and credentials”.
Procedure
- Navigate to the Fabric8 Launcher URL in a browser.
- Follow the on-screen instructions to create your example in Node.js. When asked about which deployment type, select I will build and run locally.
- Follow on-screen instructions. - When done, click the Download as ZIP file button and store the file on your hard drive. 
5.6.5.3. Authenticating the oc CLI client
						To work with example applications on Minishift or CDK using the oc command-line client, you must authenticate the client using the token provided by the Minishift or CDK web interface.
					
Prerequisites
- The URL of your running Fabric8 Launcher instance and the user credentials of your Minishift or CDK. For more information, see Section 5.6.5.1, “Getting the Fabric8 Launcher tool URL and credentials”.
Procedure
- Navigate to the Minishift or CDK URL in a browser.
- Click on the question mark icon in the top right-hand corner of the Web console, next to your user name.
- Select Command Line Tools in the drop-down menu.
- 
								Copy the oc logincommand.
- Paste the command in a terminal. The command uses your authentication token to authenticate your - ocCLI client with your Minishift or CDK account.- oc login OPENSHIFT_URL --token=MYTOKEN - $ oc login OPENSHIFT_URL --token=MYTOKEN- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
5.6.5.4. Deploying the Secured example application using the oc CLI client
This section shows you how to build your Secured example application and deploy it to OpenShift from the command line.
Prerequisites
- The example application created using the Fabric8 Launcher tool on a Minishift or CDK. For more information, see Section 5.6.5.2, “Creating the Secured example application using Fabric8 Launcher”.
- Your Fabric8 Launcher URL.
- 
								The occlient authenticated. For more information, see Section 5.6.5.3, “Authenticating theocCLI client”.
Procedure
- Clone your project from GitHub. - git clone git@github.com:USERNAME/MY_PROJECT_NAME.git - $ git clone git@github.com:USERNAME/MY_PROJECT_NAME.git- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - Alternatively, if you downloaded a ZIP file of your project, extract it. - unzip MY_PROJECT_NAME.zip - $ unzip MY_PROJECT_NAME.zip- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
- Create a new OpenShift project. - oc new-project MY_PROJECT_NAME - $ oc new-project MY_PROJECT_NAME- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
- Navigate to the root directory of your application.
- Deploy the Red Hat SSO server using the - service.sso.yamlfile from your example ZIP file:- oc create -f service.sso.yaml - $ oc create -f service.sso.yaml- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
- Use - npmto start the deployment to Minishift or CDK.- npm install && npm run openshift -- \ -d SSO_AUTH_SERVER_URL=$(oc get route secure-sso -o jsonpath='{"https://"}{.spec.host}{"/auth\n"}')- $ npm install && npm run openshift -- \ -d SSO_AUTH_SERVER_URL=$(oc get route secure-sso -o jsonpath='{"https://"}{.spec.host}{"/auth\n"}')- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - These commands install any missing module dependencies, then using the Nodeshift module, deploy the example application on OpenShift. 
5.6.6. Deploying the Secured example application to OpenShift Container Platform
In addition to the Minishift or CDK, you can create and deploy the example on OpenShift Container Platform with only minor differences. The most important difference is that you need to create the example application on Minishift or CDK before you can deploy it with OpenShift Container Platform.
Prerequisites
- The example created using Minishift or CDK.
5.6.6.1. Authenticating the oc CLI client
						To work with example applications on OpenShift Container Platform using the oc command-line client, you must authenticate the client using the token provided by the OpenShift Container Platform web interface.
					
Prerequisites
- An account at OpenShift Container Platform.
Procedure
- Navigate to the OpenShift Container Platform URL in a browser.
- Click on the question mark icon in the top right-hand corner of the Web console, next to your user name.
- Select Command Line Tools in the drop-down menu.
- 
								Copy the oc logincommand.
- Paste the command in a terminal. The command uses your authentication token to authenticate your - ocCLI client with your OpenShift Container Platform account.- oc login OPENSHIFT_URL --token=MYTOKEN - $ oc login OPENSHIFT_URL --token=MYTOKEN- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
5.6.6.2. Deploying the Secured example application using the oc CLI client
This section shows you how to build your Secured example application and deploy it to OpenShift from the command line.
Prerequisites
- The example application created using the Fabric8 Launcher tool on a Minishift or CDK.
- 
								The occlient authenticated. For more information, see Section 5.6.6.1, “Authenticating theocCLI client”.
Procedure
- Clone your project from GitHub. - git clone git@github.com:USERNAME/MY_PROJECT_NAME.git - $ git clone git@github.com:USERNAME/MY_PROJECT_NAME.git- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - Alternatively, if you downloaded a ZIP file of your project, extract it. - unzip MY_PROJECT_NAME.zip - $ unzip MY_PROJECT_NAME.zip- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
- Create a new OpenShift project. - oc new-project MY_PROJECT_NAME - $ oc new-project MY_PROJECT_NAME- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
- Navigate to the root directory of your application.
- Deploy the Red Hat SSO server using the - service.sso.yamlfile from your example ZIP file:- oc create -f service.sso.yaml - $ oc create -f service.sso.yaml- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
- Use - npmto start the deployment to OpenShift Container Platform.- npm install && npm run openshift -- \ -d SSO_AUTH_SERVER_URL=$(oc get route secure-sso -o jsonpath='{"https://"}{.spec.host}{"/auth\n"}')- $ npm install && npm run openshift -- \ -d SSO_AUTH_SERVER_URL=$(oc get route secure-sso -o jsonpath='{"https://"}{.spec.host}{"/auth\n"}')- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - These commands install any missing module dependencies, then using the Nodeshift module, deploy the example application on OpenShift. 
5.6.7. Authenticating to the Secured example application API endpoint
					The Secured example application provides a default HTTP endpoint that accepts GET requests if the caller is authenticated and authorized. The client first authenticates against the Red Hat SSO server and then performs a GET request against the Secured example application using the access token returned by the authentication step.
				
5.6.7.1. Getting the Secured example application API endpoint
When using a client to interact with the example, you must specify the Secured example application endpoint, which is the PROJECT_ID service.
Prerequisites
- The Secured example application deployed and running.
- 
								The occlient authenticated.
Procedure
- In a terminal application, execute the - oc get routescommand.- A sample output is shown in the following table: - Example 5.1. List of Secured endpoints - Expand - Name - Host/Port - Path - Services - Port - Termination - secure-sso - secure-sso-myproject.LOCAL_OPENSHIFT_HOSTNAME - secure-sso - <all> - passthrough - PROJECT_ID - PROJECT_ID-myproject.LOCAL_OPENSHIFT_HOSTNAME - PROJECT_ID - <all> - sso - sso-myproject.LOCAL_OPENSHIFT_HOSTNAME - sso - <all> - In the above example, the example endpoint would be - http://PROJECT_ID-myproject.LOCAL_OPENSHIFT_HOSTNAME.- PROJECT_IDis based on the name you entered when generating your example using developers.redhat.com/launch or the Fabric8 Launcher tool.
5.6.7.2. Authenticating HTTP requests using the command line
Request a token by sending a HTTP POST request to the Red Hat SSO server. In the following example, the jq CLI tool is used to extract the token value from the JSON response.
Prerequisites
- The secured example endpoint URL. For more information, see Section 5.6.7.1, “Getting the Secured example application API endpoint”.
- 
								The jqcommand-line tool (optional). To download the tool and for more information, see https://stedolan.github.io/jq/.
Procedure
- Request an access token with - curl, the credentials, and- <SSO_AUTH_SERVER_URL>and extract the token from the response with the- jqcommand:- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - <SSO_AUTH_SERVER_URL>is the url of the- secure-ssoservice.- The attributes, such as - username,- password, and- client_secretare usually kept secret, but the above command uses the default provided credentials with this example for demonstration purpose.- If you do not want to use - jqto extract the token, you can run just the- curlcommand and manually extract the access token.Note- The - -skoption tells curl to ignore failures resulting from self-signed certificates. Do not use this option in a production environment. On macOS, you must have- curlversion- 7.56.1or greater installed. It must also be built with OpenSSL.
- Invoke the Secured service. Attach the access (bearer) token to the HTTP headers: - Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - Example 5.2. A sample - GETRequest Headers with an Access (Bearer) Token- > GET /api/greeting HTTP/1.1 > Host: <SERVICE_HOST> > User-Agent: curl/7.51.0 > Accept: */* > Authorization: Bearer <TOKEN> - > GET /api/greeting HTTP/1.1 > Host: <SERVICE_HOST> > User-Agent: curl/7.51.0 > Accept: */* > Authorization: Bearer <TOKEN>- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - <SERVICE_HOST>is the URL of the secured example endpoint. For more information, see Section 5.6.7.1, “Getting the Secured example application API endpoint”.
- Verify the signature of the access token. - The access token is a JSON Web Token, so you can decode it using the JWT Debugger: - In a web browser, navigate to the JWT Debugger website.
- Select - RS256from the Algorithm drop down menu.Note- Make sure the web form has been updated after you made the selection, so it displays the correct RSASHA256(…) information in the Signature section. If it has not, try switching to HS256 and then back to RS256. 
- Paste the following content in the topmost text box into the VERIFY SIGNATURE section: - -----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoETnPmN55xBJjRzN/cs30OzJ9olkteLVNRjzdTxFOyRtS2ovDfzdhhO9XzUcTMbIsCOAZtSt8K+6yvBXypOSYvI75EUdypmkcK1KoptqY5KEBQ1KwhWuP7IWQ0fshUwD6jI1QWDfGxfM/h34FvEn/0tJ71xN2P8TI2YanwuDZgosdobx/PAvlGREBGuk4BgmexTOkAdnFxIUQcCkiEZ2C41uCrxiS4CEe5OX91aK9HKZV4ZJX6vnqMHmdDnsMdO+UFtxOBYZio+a1jP4W3d7J5fGeiOaXjQCOpivKnP2yU2DPdWmDMyVb67l8DRA+jh0OJFKZ5H2fNgE3II59vdsRwIDAQAB -----END PUBLIC KEY----- - -----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoETnPmN55xBJjRzN/cs30OzJ9olkteLVNRjzdTxFOyRtS2ovDfzdhhO9XzUcTMbIsCOAZtSt8K+6yvBXypOSYvI75EUdypmkcK1KoptqY5KEBQ1KwhWuP7IWQ0fshUwD6jI1QWDfGxfM/h34FvEn/0tJ71xN2P8TI2YanwuDZgosdobx/PAvlGREBGuk4BgmexTOkAdnFxIUQcCkiEZ2C41uCrxiS4CEe5OX91aK9HKZV4ZJX6vnqMHmdDnsMdO+UFtxOBYZio+a1jP4W3d7J5fGeiOaXjQCOpivKnP2yU2DPdWmDMyVb67l8DRA+jh0OJFKZ5H2fNgE3II59vdsRwIDAQAB -----END PUBLIC KEY------ Copy to Clipboard Copied! - Toggle word wrap Toggle overflow Note- This is the master realm public key from the Red Hat SSO server deployment of the Secured example application. 
- Paste the - tokenoutput from the client output into the Encoded box.- The Signature Verified sign is displayed on the debugger page. 
 
5.6.7.3. Authenticating HTTP requests using the web interface
In addition to the HTTP API, the secured endpoint also contains a web interface to interact with.
The following procedure is an exercise for you to see how security is enforced, how you authenticate, and how you work with the authentication token.
Prerequisites
- The secured endpoint URL. For more information, see Section 5.6.7.1, “Getting the Secured example application API endpoint”.
Procedure
- In a web browser, navigate to the endpoint URL.
- Perform an unauthenticated request: - Click the Invoke button. - Figure 5.1. Unauthenticated Secured Example Web Interface - The services responds with an - HTTP 403 Forbiddenstatus code.Note- This is not the correct status code. It should be - HTTP 401 Unauthorized. This issue has been identified and this example will be updated as soon as it is resolved.
 
- Perform an authenticated request as a user: - Click the Login button to authenticate against Red Hat SSO. You will be redirected to the SSO server.
- Log in as the Alice user. You will be redirected back to the web interface. Note- You can see the access (bearer) token in the command line output at the bottom of the page. - Figure 5.2. Authenticated Secured Example Web Interface (as Alice) 
- Click Invoke again to access the Greeting service. - Confirm that there is no exception and the JSON response payload is displayed. This means the service accepted your access (bearer) token and you are authorized access to the Greeting service. - Figure 5.3. The Result of an Authenticated Greeting Request (as Alice) 
- Log out.
 
- Perform an authenticated request as an admininstrator: - Click the Invoke button. - Confirm that this sends an unauthenticated request to the Greeting service. 
- Click the Login button and log in as the admin user. - Figure 5.4. Authenticated Secured Example Web Interface (as admin) 
 
- Click the Invoke button. - The service responds with an - HTTP 403 Forbiddenstatus code because the admin user is not authorized to access the Greeting service.- Figure 5.5. Unauthorized Error Message 
5.6.8. Secured SSO resources
Follow the links below for additional information on the principles behind the OAuth2 specification and on securing your applications using Red Hat SSO and Keycloak:
5.7. Cache example for Node.js
The following example is not meant to be run in a production environment.
Limitation: Run this example application on a Minishift or CDK. You can also use a manual workflow to deploy this example to OpenShift Online Pro and OpenShift Container Platform. This example is not currently available on OpenShift Online Starter.
Example proficiency level: Advanced.
The Cache example demonstrates how to use a cache to increase the response time of applications.
This example shows you how to:
- Deploy a cache to OpenShift.
- Use a cache within an application.
5.7.1. How caching works and when you need it
Caches allows you to store information and access it for a given period of time. You can access information in a cache faster or more reliably than repeatedly calling the original service. A disadvantage of using a cache is that the cached information is not up to date. However, that problem can be reduced by setting an expiration or TTL (time to live) on each value stored in the cache.
Example 5.3. Caching example
Assume you have two applications: service1 and service2:
- Service1 depends on a value from service2. - If the value from service2 infrequently changes, service1 could cache the value from service2 for a period of time.
- Using cached values can also reduce the number of times service2 is called.
 
- If it takes service1 500 ms to retrieve the value directly from service2, but 100 ms to retrieve the cached value, service1 would save 400 ms by using the cached value for each cached call.
- If service1 would make uncached calls to service2 5 times per second, over 10 seconds, that would be 50 calls.
- If service1 started using a cached value with a TTL of 1 second instead, that would be reduced to 10 calls over 10 seconds.
How the Cache example works
- The cache, cute name, and greeting services are deployed and exposed.
- User accesses the web frontend of the greeting service.
- User invokes the greeting HTTP API using a button on the web frontend.
- The greeting service depends on a value from the cute name service. - The greeting service first checks if that value is stored in the cache service. If it is, then the cached value is returned.
- If the value is not cached, the greeting service calls the cute name service, returns the value, and stores the value in the cache service with a TTL of 5 seconds.
 
- The web front end displays the response from the greeting service as well as the total time of the operation.
- User invokes the service multiple times to see the difference between cached and uncached operations. - Cached operations are significantly faster than uncached operations.
- User can force the cache to be cleared before the TTL expires.
 
5.7.2. Deploying the Cache example application to OpenShift Online
Use one of the following options to execute the Cache example application on OpenShift Online.
					Although each method uses the same oc commands to deploy your application, using developers.redhat.com/launch provides an automated deployment workflow that executes the oc commands for you.
				
5.7.2.1. Deploying the example application using developers.redhat.com/launch
This section shows you how to build your REST API Level 0 example application and deploy it to OpenShift from the Red Hat Developer Launcher web interface.
Prerequisites
- An account at OpenShift Online.
Procedure
- Navigate to the developers.redhat.com/launch URL in a browser.
- Follow on-screen instructions to create and launch your example application in Node.js.
5.7.2.2. Authenticating the oc CLI client
						To work with example applications on OpenShift Online using the oc command-line client, you must authenticate the client using the token provided by the OpenShift Online web interface.
					
Prerequisites
- An account at OpenShift Online.
Procedure
- Navigate to the OpenShift Online URL in a browser.
- Click on the question mark icon in the top right-hand corner of the Web console, next to your user name.
- Select Command Line Tools in the drop-down menu.
- 
								Copy the oc logincommand.
- Paste the command in a terminal. The command uses your authentication token to authenticate your - ocCLI client with your OpenShift Online account.- oc login OPENSHIFT_URL --token=MYTOKEN - $ oc login OPENSHIFT_URL --token=MYTOKEN- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
5.7.2.3. Deploying the Cache example application using the oc CLI client
This section shows you how to build your Cache example application and deploy it to OpenShift from the command line.
Prerequisites
- The example application created using developers.redhat.com/launch. For more information, see Section 5.7.2.1, “Deploying the example application using developers.redhat.com/launch”.
- 
								The occlient authenticated. For more information, see Section 5.7.2.2, “Authenticating theocCLI client”.
Procedure
- Clone your project from GitHub. - git clone git@github.com:USERNAME/MY_PROJECT_NAME.git - $ git clone git@github.com:USERNAME/MY_PROJECT_NAME.git- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - Alternatively, if you downloaded a ZIP file of your project, extract it. - unzip MY_PROJECT_NAME.zip - $ unzip MY_PROJECT_NAME.zip- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
- Create a new project. - oc new-project MY_PROJECT_NAME - $ oc new-project MY_PROJECT_NAME- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
- Navigate to the root directory of your application.
- Deploy the cache service. - oc apply -f service.cache.yml - $ oc apply -f service.cache.yml- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow Note- If you are using an architecture other than x86_64, in the YAML file, update the image name of Red Hat Data Grid to its relevant image name in that architecture. For example, for the s390x architecture, update the image name to its IBM Z image name - registry.access.redhat.com/jboss-datagrid-7/datagrid73-openj9-11-openshift-rhel8, and for the ppc64le architecture, update the image name to its IBM Power Systems image name- registry.access.redhat.com/jboss-datagrid-7/datagrid73-openj9-11-openshift-rhel8.
- Use - start-openshift.shto start the deployment to OpenShift.- ./start-openshift.sh - $ ./start-openshift.sh- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
- Check the status of your application and ensure your pod is running. - Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - Your 3 pods should have a status of - Runningonce they are fully deployed and started.
- After your example application is deployed and started, determine its route. - Example Route Information - oc get routes - $ oc get routes NAME HOST/PORT PATH SERVICES PORT TERMINATION MY_APP_NAME-cutename MY_APP_NAME-cutename-MY_PROJECT_NAME.OPENSHIFT_HOSTNAME MY_APP_NAME-cutename 8080 None MY_APP_NAME-greeting MY_APP_NAME-greeting-MY_PROJECT_NAME.OPENSHIFT_HOSTNAME MY_APP_NAME-greeting 8080 None- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - The route information of a pod gives you the base URL which you use to access it. In the example above, you would use - http://MY_APP_NAME-greeting-MY_PROJECT_NAME.OPENSHIFT_HOSTNAMEas the base URL to access the greeting service.
5.7.3. Deploying the Cache example application to Minishift or CDK
Use one of the following options to execute the Cache example application locally on Minishift or CDK:
					Although each method uses the same oc commands to deploy your application, using Fabric8 Launcher provides an automated deployment workflow that executes the oc commands for you.
				
5.7.3.1. Getting the Fabric8 Launcher tool URL and credentials
You need the Fabric8 Launcher tool URL and user credentials to create and deploy example applications on Minishift or CDK. This information is provided when the Minishift or CDK is started.
Prerequisites
- The Fabric8 Launcher tool installed, configured, and running.
Procedure
- Navigate to the console where you started Minishift or CDK.
- Check the console output for the URL and user credentials you can use to access the running Fabric8 Launcher: - Example Console Output from a Minishift or CDK Startup - Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
5.7.3.2. Deploying the example application using the Fabric8 Launcher tool
This section shows you how to build your REST API Level 0 example application and deploy it to OpenShift from the Fabric8 Launcher web interface.
Prerequisites
- The URL of your running Fabric8 Launcher instance and the user credentials of your Minishift or CDK. For more information, see Section 5.7.3.1, “Getting the Fabric8 Launcher tool URL and credentials”.
Procedure
- Navigate to the Fabric8 Launcher URL in a browser.
- Follow the on-screen instructions to create and launch your example application in Node.js.
5.7.3.3. Authenticating the oc CLI client
						To work with example applications on Minishift or CDK using the oc command-line client, you must authenticate the client using the token provided by the Minishift or CDK web interface.
					
Prerequisites
- The URL of your running Fabric8 Launcher instance and the user credentials of your Minishift or CDK. For more information, see Section 5.7.3.1, “Getting the Fabric8 Launcher tool URL and credentials”.
Procedure
- Navigate to the Minishift or CDK URL in a browser.
- Click on the question mark icon in the top right-hand corner of the Web console, next to your user name.
- Select Command Line Tools in the drop-down menu.
- 
								Copy the oc logincommand.
- Paste the command in a terminal. The command uses your authentication token to authenticate your - ocCLI client with your Minishift or CDK account.- oc login OPENSHIFT_URL --token=MYTOKEN - $ oc login OPENSHIFT_URL --token=MYTOKEN- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
5.7.3.4. Deploying the Cache example application using the oc CLI client
This section shows you how to build your Cache example application and deploy it to OpenShift from the command line.
Prerequisites
- The example application created using Fabric8 Launcher tool on a Minishift or CDK. For more information, see Section 5.7.3.2, “Deploying the example application using the Fabric8 Launcher tool”.
- Your Fabric8 Launcher tool URL.
- 
								The occlient authenticated. For more information, see Section 5.7.3.3, “Authenticating theocCLI client”.
Procedure
- Clone your project from GitHub. - git clone git@github.com:USERNAME/MY_PROJECT_NAME.git - $ git clone git@github.com:USERNAME/MY_PROJECT_NAME.git- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - Alternatively, if you downloaded a ZIP file of your project, extract it. - unzip MY_PROJECT_NAME.zip - $ unzip MY_PROJECT_NAME.zip- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
- Create a new project. - oc new-project MY_PROJECT_NAME - $ oc new-project MY_PROJECT_NAME- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
- Navigate to the root directory of your application.
- Deploy the cache service. - oc apply -f service.cache.yml - $ oc apply -f service.cache.yml- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow Note- If you are using an architecture other than x86_64, in the YAML file, update the image name of Red Hat Data Grid to its relevant image name in that architecture. For example, for the s390x architecture, update the image name to its IBM Z image name - registry.access.redhat.com/jboss-datagrid-7/datagrid73-openj9-11-openshift-rhel8, and for the ppc64le architecture, update the image name to its IBM Power Systems image name- registry.access.redhat.com/jboss-datagrid-7/datagrid73-openj9-11-openshift-rhel8.
- Use - start-openshift.shto start the deployment to OpenShift.- ./start-openshift.sh - $ ./start-openshift.sh- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow 
- Check the status of your application and ensure your pod is running. - Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - Your 3 pods should have a status of - Runningonce they are fully deployed and started.
- After your example application is deployed and started, determine its route. - Example Route Information - oc get routes - $ oc get routes NAME HOST/PORT PATH SERVICES PORT TERMINATION MY_APP_NAME-cutename MY_APP_NAME-cutename-MY_PROJECT_NAME.OPENSHIFT_HOSTNAME MY_APP_NAME-cutename 8080 None MY_APP_NAME-greeting MY_APP_NAME-greeting-MY_PROJECT_NAME.OPENSHIFT_HOSTNAME MY_APP_NAME-greeting 8080 None- Copy to Clipboard Copied! - Toggle word wrap Toggle overflow - The route information of a pod gives you the base URL which you use to access it. In the example above, you would use - http://MY_APP_NAME-greeting-MY_PROJECT_NAME.OPENSHIFT_HOSTNAMEas the base URL to access the greeting service.
5.7.4. Deploying the Cache example application to OpenShift Container Platform
The process of creating and deploying example applications to OpenShift Container Platform is similar to OpenShift Online:
Prerequisites
- The example application created using developers.redhat.com/launch.
Procedure
- Follow the instructions in Section 5.7.2, “Deploying the Cache example application to OpenShift Online”, only use the URL and user credentials from the OpenShift Container Platform Web Console.
5.7.5. Interacting with the unmodified Cache example application
Use the default web interface to interact with the unmodified Cache example application, and see how storing frequently accessed data can shorten the time needed to access your service.
Prerequisites
- Your application deployed
Procedure
- 
							Navigate to the greetingservice using your browser.
- Click Invoke the service once. - Notice the - durationvalue is above- 2000. Also notice the cache state has changed from- No cached valueto- A value is cached.
- Wait 5 seconds and notice cache state has changed back to - No cached value.- The TTL for the cached value is set to 5 seconds. When the TTL expires, the value is no longer cached. 
- Click Invoke the service once more to cache the value.
- Click Invoke the service a few more times over the course of a few seconds while cache state is - A value is cached.- Notice a significantly lower - durationvalue since it is using a cached value. If you click Clear the cache, the cache is emptied.
5.7.6. Caching resources
More background and related information on caching can be found here:
 
     
     
     
    