Find the Best Cosmetic Hospitals

Explore trusted cosmetic hospitals and make a confident choice for your transformation.

โ€œInvest in yourself โ€” your confidence is always worth it.โ€

Explore Cosmetic Hospitals

Start your journey today โ€” compare options in one place.

Openshift: Lab 8 – Work with databases in OpenShift using the oc CLI tool

In this lesson, you will learn how to create an instance of a database in the Developer Sandbox using the oc CLI tool, and ultimately bind a Node.js application to that database.

What you need to know

In order to get full benefit from this lesson you need to:

  • Understand howย Kubernetesย is the foundational technology forย OpenShift.
  • Know how to access the Developer Sandbox via web browser.
  • Know how to use theย ocย CLI tool installed on your local computer to interact with a remote instance of the Developer Sandbox.
  • Understand how environment variables provide information to an application at runtime.

What you will learn

In this lesson you will learn:

  • How to create an instance of a database in Developer Sandbox using theย ocย CLI tool.
  • How to create an instance of a Node.js application from source code stored in GitHub using theย ocย CLI tool.
  • How to bind the Node.js application to the database running in OpenShiftย using theย ocย CLI tool.

Understand the demonstration scenario

The objective of this lesson is to demonstrate how to install and run a Node.js application bound to a database installed using the oc CLI tool. Both the Node.js application and the database will run in the Developer Sandbox.

The Node.js application publishes a web page that allows users to retrieve a name at random, then store that random name in the database to which the application is bound. Also, the Node.js application web page displays a list of names stored in the database (Figure 1).

The Node.js demonstration application allows users to get, store, and list random names.
Figure 1: The Node.js demonstration application allows users to get, store, and list random names.

The demonstration scenario uses a MongoDB database which you will install using the oc CLI tool. Also, you will install the Node.js application in OpenShift using the oc CLI tool.

The Node.js application has a server-side API that stores and retrieves data stored in the MongoDB database. This application also publishes a web page that is bound to the server-side API. Users interact with the page, and the page, in turn, interacts with the server-side API (Figure 2).

The demonstration project binds a Node.js application running in the sandbox to an instance of a database thatโ€™s also running in OpenShift.
Figure 2: The demonstration project binds a Node.js application running in the sandbox to an instance of a database thatโ€™s also running in OpenShift.

Node.js binds to the MongoDB database by way of a connection URL that is created by OpenShift during the database installation process. The URL contains the username and password information. You will declare the username and password information when you install the MongoDB database.

The Node.js application references the MongoDB connection URL to create a connection to the database. The way that the application knows the connection URL is by way of an environment variable thatโ€™s created as part of the process of installing Node.js in the Developer Sandbox.

In the sections that follow, you will learn how to install the MongoDB database and install the Node.js application along with the steps necessary to expose and consume the MongoDB connection URL.

Get login credentials for the OpenShift web console

In order to use the oc CLI tool to access a remote instance of the Developer Sandbox, you need to get a special set of login credentials that are available from within the OpenShift web console.

The following steps describe how to get the necessary login credentials:

  1. Go to the web console for theย Developer Sandboxย and click theย question markย in the upper right corner of the web consoleย (Figure 3, Callout 1).
  2. Selectย Command line toolsย from the drop-down. This actionย opens theย Command line toolsย web pageย (Figure 3, Callout 2).
  3. Selectย Copy command loginย (Figure 3, Callout 3).ย Figure 3: Access Command line tools by clicking the question mark in the upper right corner of the OpenShift web console.
  4. A page with the optionย Display Tokenย will appear. Selectย Display Tokenย (Figure 4, Callout 1).
  5. A page withย login credentials will appear. Copy the content of theย Display Tokenย field and paste it into theย Log in with this tokenย fieldย (Figure 4, Callout 2).ย Figure 4: Clicking Display Token displays a page with login credentials.
  6. Go to a terminal running on your local machine and paste in the login text you copied, then selectย Enterย to log in to the Developer Sandboxย (Figure 5).ย Figure 5: With your login token, use the oc CLI tool to access the remote Developer Sandbox from your local machine.

Once logged in, you can do work in the remote Developer Sandbox using the oc CLI tool.

Install the database

Once you have logged into the Developer Sandbox using the oc CLI tool on your local machine, you are ready to install the database that the demonstration application will use. In this step, you will install an instance of MongoDB using an OpenShift template.

While OpenShift includes templates for multiple databases, it does not include a template for MongoDB. Thatโ€™s not a problem; we can install it at the command line. First, use the following command to get the name of your projectโ€“which, in Kubernetes-speak, is the namespace:

oc get projectCode language: JavaScript (javascript)

Copy snippet

Now, use the namespace in the following commands:

oc create -f 
https://raw.githubusercontent.com/openshift-labs/starter-guides/ocp-4.8/mongodb-template.yaml -n {your-namespace}

oc new-app --template=mongodb-ephemeral --param MONGODB_USER=genuser --param MONGODB_PASSWORD=password --param MONGODB_DATABASE=namegen --param NAMESPACE={your-namespace}

oc import-image mongodb:3.6 
--from=registry.access.redhat.com/rhscl/mongodb-36-rhel7 --confirm -n {your-namespace}Code language: JavaScript (javascript)

Copy snippet

About these parameters: 

  • --template=mongodb-persistentย  declares the OpenShift template to use, in this case theย mongodb-persistentย template. Theย mongodb-persistentย template creates a Kubernetes persistent volume claim (PVC) for storing database data. The data stored in the PVC will remain available even if the instance of the MongoDB database is removed from the Developer Sandbox.ย 
  • --param=MONGODB_USER=genuserย declares the name of the MongoDB user who will be reading and writing to the instance of the MongoDB database running in the Developer Sandbox.ย 
  • --param=MONGODB_PASSWORD=passwordย declares the password for the MongoDB user who will be reading and writing to the instance of the MongoDB database running in the Developer Sandbox.ย 
  • --param=MONGODB_DATABASE=namegenย declares the name of the database in the MongoDB instance that will be created to store data for the demonstration application.

After you execute the command shown above, you will see output similar to this:


--> Deploying template "openshift/mongodb-persistent" to project <your_redhat-login_name>-dev

     MongoDB

     ---------

     MongoDB database service, with persistent storage. For more information about using this template, including OpenShift considerations, see documentation in the upstream repository: https://github.com/sclorg/mongodb-container.

     NOTE: Scaling to more than one replica is not supported. You must have persistent volumes available in your cluster to use this template.

     The following service(s) have been created in your project: mongodb.

            Username: genuser

            Password: password

       Database Name: namegen

      Connection URL: mongodb://genuser:password@mongodb/namegen   

     For more information about using this template, including OpenShift considerations, see documentation in the upstream repository: https://github.com/sclorg/mongodb-container.

     * With parameters:

        * Memory Limit=512Mi

        * Namespace=openshift

        * Database Service Name=mongodb

        * MongoDB Connection Username=genuser

        * MongoDB Connection Password=password

        * MongoDB Database Name=namegen

        * MongoDB Admin Password=0SNxmy1woMqOuFye # generated

        * Volume Capacity=1Gi

        * Version of MongoDB Image=3.6

--> Creating resources ...

    secret "mongodb" created

    service "mongodb" created

    persistentvolumeclaim "mongodb" created

    deploymentconfig.apps.openshift.io "mongodb" created

--> Success

    Application is not exposed. You can expose services to the outside world by executing one or more of the commands below:

     'oc expose service/mongodb' 

    Run 'oc status' to view your app.Code language: PHP (php)

Copy snippet

After the MongoDB database is installed and running in the Developer Sandbox, you will install a Node.js application that uses the MongoDB database.

Install the Node.js application

Run the following steps in the terminal window of your local machine to install the demonstration application in the Developer Sandbox. Copy and paste the following oc new app command into the terminal on your local machine:

oc new-app https://github.com/redhat-developer-demos/namegen --name=namegen-app --env=MONGODB_URL=mongodb://genuser:password@mongodb/namegenCode language: JavaScript (javascript)

Copy snippet

About these parameters: 

  • https://github.com/redhat-developer-demos/namegenย is the location of the source code where the Node.js application is stored on GitHub. OpenShift will retrieve the source code from GitHub and use it to create a Linux container that will be part of theย Kubernetes Deploymentย under which the application can be run in the Developer Sandbox.
  • --name=namegen-appย declares the name that will be associated with the Node.js application inside the Developer Sandbox/Openshift cluster.
  • --env=MONGODB_URL=mongodb://genuser:password@mongodb/namegenย uses theย โ€“envย command-line option to declare the environment variableย MONGODB_URLย which will be injected into each container running the deployment of the Node.js application running in the Developer Sandbox/OpenShift cluster. This environment variable describes the connection URL that the Node.js application uses to connect to the instance of MongoDB that you already installed.

After you execute the command shown above, youโ€™ll see output similar to this:

--> Found image dfd08e2 (7 months old) in image stream "openshift/nodejs" under tag "16-ubi8" for "nodejs"

    Node.js 16 

    ---------- 

    Node.js 16 available as container is a base platform for building and running various Node.js 16 applications and frameworks. Node.js is a platform built on Chrome's JavaScript runtime for easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.

    Tags: builder, nodejs, nodejs16

    * The source repository appears to match: nodejs

    * A source build using source code from https://github.com/redhat-developer-demos/namegen will be created

      * The resulting image will be pushed to image stream tag "namegen-app:latest"

      * Use 'oc start-build' to trigger a new build


--> Creating resources ...

    imagestream.image.openshift.io "namegen-app" created

    buildconfig.build.openshift.io "namegen-app" created

    deployment.apps "namegen-app" created

    service "namegen-app" created

--> Success

    Build scheduled, use 'oc logs -f buildconfig/namegen-app' to track its progress.

    Application is not exposed. You can expose services to the outside world by executing one or more of the commands below:

     'oc expose service/namegen-app' 

    Run 'oc status' to view your app.Code language: PHP (php)

Copy snippet

Verify the installation

At this point, the MongoDB instance and Node.js application are installed and running in the Developer Sandbox. To verify that they are indeed up and running, copy and paste the following oc status command into the terminal on your local machine: 

oc status

Copy snippet

You will see output similar to the following, which indicates that both the MongoDB instance and Node.js namegen application are up and running:

In project <red_hat_username>-dev on server https://api.sandbox.x8i5.p1.openshiftapps.com:6443

svc/mongodb - 172.30.58.199:27017

  dc/mongodb deploys openshift/mongodb:3.6 

    deployment #1 deployed 20 minutes ago - 1 pod

http://namegen-app-<red_hat_username>-dev.apps.sandbox.x8i5.p1.openshiftapps.com to pod port 8080-tcp (svc/namegen-app)

  deployment/namegen-app deploys istag/namegen-app:latest <-

    bc/namegen-app source builds https://github.com/redhat-developer-demos/namegen on openshift/nodejs:16-ubi8 

    deployment #2 running for 20 minutes - 1 pod

    deployment #1 deployed 20 minutes agoCode language: PHP (php)

Copy snippet

You are now ready to expose the namegen application to the internet so that it can be used in a web browser.

Expose the Node.js application to the Internet

To expose the namegen application to the Internet by using the oc expose command, copy and paste the following oc expose command into the terminal on your local machine: 

oc expose service/namegen-app

Copy snippet

You will get output similar to the following:

route.route.openshift.io/namegen-app exposed

Copy snippet

Running oc expose creates an OpenShift route. An OpenShift route is associated with a URL that allows access to the Node.js namegen application from the internet. 

Exercise the demonstration application

To exercise the demonstration application, use the oc get route command to determine the URL for the Node.js namegen application. Run the following oc get route command into the terminal on your local machine: 

oc get routeCode language: JavaScript (javascript)

Copy snippet

You will get output similar to the following. Notice that the URL to the application is reported by the string in the PATH column:

NAME          HOST/PORT                                                         PATH   SERVICES      PORT       TERMINATION   WILDCARD

namegen-app   namegen-app-<your_redhat-login_name>-dev.apps.sandbox.x8i5.p1.openshiftapps.com          namegen-app   8080-tcp                 None

Code language: HTML, XML (xml)

Copy snippet

Now, copy the URL reported in the output from oc get route into the address bar on your browser. The URL you copy will be similar to the following:

namegen-app--dev.apps.sandbox.x8i5.p1.openshiftapps.com

About the parameters:

  • your_redhat-login_nameย is your login name.
  • apps.sandbox.x8i5.p1.openshiftapps.comย represents a unique domain name for the particular Developer Sandbox instance. In this case, the domain name is special to the Developer Sandbox user taking this lesson.

Copying the URL thatโ€™s reported by oc get route into a web browser will render the Random Name Generator and Save window (Figure 6).

The Node.js demonstration application generates a random name on demand and then adds the name to a list of names stored in the MongoDB database.
Figure 6: The Node.js demonstration application generates a random name on demand and then adds the name to a list of names stored in the MongoDB database.

The Node.js namegen application is now up and running. You can exercise the application by selecting Get Random Name.

An automatically generated random name will appear. Select Save Name to add the newly created random name to the list of names.

Summary

In this lesson, you learned how to use the oc CLI tool to install an instance of MongoDB and a Node.js application named namegen into the Developer Sandbox and installed the MongoDB instance from an OpenShift template available in the OpenShift Developer Catalog. You also installed the Node.js application from source code stored on GitHub and learned how to configure both the  MongoDB instance and Node.js application by declaring command-line options.

In addition, you used the oc expose command to create a route to the Node.js namegen application thatโ€™s accessible from the internet. Then you used the oc get route command to discover the URL created by the oc expose command.

Finally, you exercised the Node.js application by pasting the applicationโ€™s URL into a web browser and interacting with the application’s web page.

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services โ€” all in one place.

Explore Hospitals
Iโ€™m a DevOps/SRE/DevSecOps/Cloud Expert passionate about sharing knowledge and experiences. I have worked at <a href="https://www.cotocus.com/">Cotocus</a>. I share tech blog at <a href="https://www.devopsschool.com/">DevOps School</a>, travel stories at <a href="https://www.holidaylandmark.com/">Holiday Landmark</a>, stock market tips at <a href="https://www.stocksmantra.in/">Stocks Mantra</a>, health and fitness guidance at <a href="https://www.mymedicplus.com/">My Medic Plus</a>, product reviews at <a href="https://www.truereviewnow.com/">TrueReviewNow</a> , and SEO strategies at <a href="https://www.wizbrand.com/">Wizbrand.</a> Do you want to learn <a href="https://www.quantumuting.com/">Quantum Computing</a>? <strong>Please find my social handles as below;</strong> <a href="https://www.rajeshkumar.xyz/">Rajesh Kumar Personal Website</a> <a href="https://www.youtube.com/TheDevOpsSchool">Rajesh Kumar at YOUTUBE</a> <a href="https://www.instagram.com/rajeshkumarin">Rajesh Kumar at INSTAGRAM</a> <a href="https://x.com/RajeshKumarIn">Rajesh Kumar at X</a> <a href="https://www.facebook.com/RajeshKumarLog">Rajesh Kumar at FACEBOOK</a> <a href="https://www.linkedin.com/in/rajeshkumarin/">Rajesh Kumar at LINKEDIN</a> <a href="https://www.wizbrand.com/rajeshkumar">Rajesh Kumar at WIZBRAND</a> <a href="https://www.rajeshkumar.xyz/dailylogs">Rajesh Kumar DailyLogs</a>

Related Posts

List of all Job Roles, Job Titles in Software and IT Companies

The software and IT industry is home to a diverse array of job roles and titles, reflecting the dynamic and ever-evolving nature of technology. From core technical…

Read More

Best DevOps Tools in 2024

hereโ€™s a clear, structured breakdown of the Best DevOps Tools (grouped by categories), so you can use it for learning, training, or posts. ๐Ÿš€ Best DevOps Tools…

Read More

OpenShift Install & Configurations using OpenShift Local in windows laptops/desktops

Below is the 100% correct and updated step-by-step guide to install and configure OpenShift Local (aka CRC) on Windows 10/11 laptops or desktops using the correct crc…

Read More

Openshift: How to configure Azure openshift ARO with Custom Domain

Step-by-Step Guide: Configuring Azure Red Hat OpenShift (ARO) with a Custom Domain Setting up a custom domain for your ARO cluster involves both Azure and DNS provider…

Read More

Openshift: Lab 10 – View performance information using the OpenShift web console

Rajesh Kumar Iโ€™m a DevOps/SRE/DevSecOps/Cloud Expert passionate about sharing knowledge and experiences. I have worked at Cotocus. I share tech blog at DevOps School, travel stories at…

Read More

Openshift: How to add Helm Repository in Openshift

Adding a Helm repository in OpenShift is a common step to manage and deploy Helm charts in your OpenShift cluster. OpenShift supports Helm CLI out of the…

Read More
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x