| subcollection | solution-tutorials | ||
|---|---|---|---|
| copyright |
|
||
| lastupdated | 2019-08-13 | ||
| lasttested | 2019-07-30 |
{:shortdesc: .shortdesc} {:new_window: target="_blank"} {:codeblock: .codeblock} {:screen: .screen} {:tip: .tip} {:pre: .pre}
{: #scalable-webapp-openshift}
This tutorial walks you through how to scaffold a web application, run it locally in a container, push the scaffolded code to a private Git repository and then deploy it to a {{site.data.keyword.openshiftlong_notm}} cluster. Additionally, you will learn how expose the app on an {{site.data.keyword.openshiftshort}} route, bind a custom domain, monitor the health of the environment, and scale the application. {:shortdesc}
With the {{site.data.keyword.openshiftlong_notm}}, you can create {{site.data.keyword.containerlong_notm}} clusters with worker nodes that come installed with the {{site.data.keyword.openshiftlong_notm}} Container Platform orchestration software. You get all the advantages of managed {{site.data.keyword.containerlong_notm}} for your cluster infrastructure environment, while using the {{site.data.keyword.openshiftshort}} tooling and catalog that runs on Red Hat Enterprise Linux for your app deployments.
For developers looking to kickstart their projects, the {{site.data.keyword.dev_cli_notm}} CLI enables rapid application development and deployment by generating template applications that you can run immediately or customize as the starter for your own solutions.
{: #objectives}
- Scaffold a starter application.
- Deploy the application to the {{site.data.keyword.openshiftlong_notm}} cluster.
- Bind a custom domain.
- Monitor the logs and health of the cluster.
- Scale {{site.data.keyword.openshiftshort}} pods.
{: #services}
This tutorial uses the following runtimes and services:
This tutorial may incur costs. Use the Pricing Calculator to generate a cost estimate based on your projected usage.
{: #architecture}
- A developer generates a starter application with {{site.data.keyword.dev_cli_notm}}.
- The dev adds the generated starter kit code to a private Git repository on {{site.data.keyword.Bluemix_notm}}
- A Docker container image is build from the code.
- The image is pushed to a namespace in {{site.data.keyword.registrylong_notm}}.
- The application is deployed to an {{site.data.keyword.openshiftshort}} cluster by pulling the image.
- Users access the application.
{: #prereqs}
- Install {{site.data.keyword.dev_cli_notm}} - Script to install docker, kubectl, ibmcloud cli and required plug-ins like dev, ks, cr ...
- Install the {{site.data.keyword.openshiftshort}} Origin (oc) CLI
- Configure your access to {{site.data.keyword.Bluemix_notm}} Git to be able to commit source code to a private Git repository.
- Use these instructions to generate a new SSH key pair if you don't have one.
- And add your SSH public key to your Git settings.
- Set up the {{site.data.keyword.registrylong_notm}} CLI and your registry namespace
{: #create_openshift_cluster}
With {{site.data.keyword.openshiftlong_notm}}, you have a fast and secure way to containerize and deploy enterprise workloads in {{site.data.keyword.openshiftshort}} clusters. {{site.data.keyword.openshiftshort}} clusters build on Kubernetes container orchestration that offers consistency and flexibility for your development lifecycle operations.
In this section, you will provision a {{site.data.keyword.openshiftlong_notm}} cluster with two worker nodes.
- Create an {{site.data.keyword.openshiftshort}} cluster from the {{site.data.keyword.Bluemix}} catalog.
- Set Cluster name to myopenshiftcluster.
- Select a Resource group and choose a Geography.
- Under Location,
- Select a Metro.
- Choose a single Worker zone by unchecking the other worker zones.
- Select Public endpoint only as your Master service endpoint.
- Under Default worker pool,
- Choose {{site.data.keyword.openshiftshort}} 3.11 as your cluster type and version.
- Select 4 Cores 16GB RAM as the flavor for Worker nodes.
- Leave Encrypt local disk checked and select 2 Worker nodes for this tutorial.
- Review Infrastructure permissions checker to verify the required permissions
- Click Create cluster to provision an {{site.data.keyword.openshiftshort}} cluster.
In this step, you'll configure oc to point to your newly created cluster. The {{site.data.keyword.openshiftshort}} Container Platform CLI exposes commands for managing your applications, as well as lower level tools to interact with each component of your system. The CLI is available using the oc command.
- When the cluster is ready, click on the Access tab under the cluster name.
- Under After your cluster provisions, gain access section, click on oauth token request page link and follow instructions to log into your cluster on a terminal.
- Once logged-in using the
oc logincommand, run the below command to see all the namespaces in your cluster{:pre}oc get ns
{: #generate_starter_kit}
The ibmcloud dev tooling greatly cuts down on development time by generating application starters with all the necessary boilerplate, build and configuration code so that you can start coding business logic faster.
-
On a terminal, start the
ibmcloud devwizard by running the below commandibmcloud dev create
{: pre}
You may be asked to target an organization and a space, follow the instructions on the CLI {:tip}
-
Select
Backend Service / Web AppthenNodeand selectNode.js Web App with Express.jsto create a Node starter. -
Enter a name for your application.
-
Select a resource group same as the cluster to deploy this application.
-
Do not add additional services.
-
Do not add a DevOps toolchain, select manual deployment.
This generates a starter application complete with the code and all the necessary configuration files for local development and deployment to cloud on Cloud Foundry or {{site.data.keyword.containershort_notm}}.
You can build and run the application as you normally would using npm for node development. You can also build a docker image and run the application in a container to ensure consistent execution locally and on the cloud. Use the following steps to build your docker image.
-
Ensure your local Docker engine is started.
docker ps
{: pre}
-
Change to the directory of the generated project.
cd <project name>
{: pre}
-
Build the application.
ibmcloud dev build
{: pre} This might take a few minutes to run as all the application dependencies are downloaded and a Docker image, which contains your application and all the required environment, is built.
-
Run the container.
ibmcloud dev run
{: pre}
This uses your local Docker engine to run the docker image that you built in the previous step.
-
After your container starts, go to
http://localhost:3000/.
In this step, you will create a private IBM Cloud Git repository and push the generated code.
-
On a browser, open IBM Cloud Git
The link above is for
us-southregion. For other regions, runibmcloud regionsand replaceus-southin the URL with region name. {:tip} -
Click on New project and provide
openshiftappas the project name. -
Set the visibility level to Private and click Create project
-
Follow the instructions under Git global setup and Existing folder sections to setup Git and to import the code you have generated with
ibmcloud dev. -
Once you push the code to the private repository, you should see the scaffolded code in the project.
In this step, you will create a deploy token to allow read-only access to your repository
- To create a Deploy token,
- On the left pane of the Git repo page, click Settings > Repository
- Click on Expand next to Deploy Tokens.
- Provide foropenshift as the name then check read_repository checkbox and click create deploy token.
- Save the generated username and password for future reference.
- Click on Project then click Details, click on Clone and copy Clone with HTTPS URL.Save the URL for future reference.
{: #create_openshift_app} In this section, you will generate a BuildConfig YAML file and update the file with Private registry details to push the generated builder Docker image to {{site.data.keyword.registryshort_notm}}.
A Kubernetes namespace provides a mechanism to scope resources in a cluster. In {{site.data.keyword.openshiftshort}}, a project is a Kubernetes namespace with additional annotations.
-
Create a new project
oc new-project openshiftproject
{:pre}
-
Generate a yaml file
openshift.yamlin the same folder as your starter kit code by replacing the placeholders and running the below commandoc new-app https://<DEPLOY_TOKEN_USERNAME>:<DEPLOY_TOKEN_PASSWORD>@<REPO_URL_WITHOUT_HTTPS> --name=openshiftapp --strategy=docker -o yaml > openshift.yaml
{:pre}
Replace
<REPO_URL_WITHOUT_HTTPS>with the Git repository URL withouthttps://. {:tip}
In this step, you will update the generated BuildConfig section of the generated yaml to point to {{site.data.keyword.registryshort_notm}} namespace and push the generated builder image to {{site.data.keyword.registryshort_notm}}. In this tutorial, a remote private {{site.data.keyword.registryshort_notm}} is used for persistent storage of created images.
-
To automate access to your registry namespaces and to push generated builder Docker image to {{site.data.keyword.registryshort_notm}}, create a secret using an IAM API key
oc create secret docker-registry push-secret --docker-username=iamapikey --docker-password=<API_KEY> --docker-server=<REGISTRY_URL>
{:pre}
For creating an API key, refer this link. For registry URL, run
ibmcloud cr region. {:tip} -
Edit the generated openshift.yaml.
-
Locate the ImageStream object named openshiftapp and add a
dockerImageRepositorydefinition underspecreplacing the placeholders<REGISTRY_URL>and<REGISTRY_NAMESPACE>with their respective values:- apiVersion: image.openshift.io/v1 kind: ImageStream metadata: annotations: openshift.io/generated-by: OpenShiftNewApp creationTimestamp: null labels: app: openshiftapp name: openshiftapp spec: dockerImageRepository: <REGISTRY_URL>/<REGISTRY_NAMESPACE>/openshiftapp lookupPolicy: local: false status: dockerImageRepository: ""
{:codeblock}
An image stream and its associated tags provide an abstraction for referencing container images from within {{site.data.keyword.openshiftshort}} Container Platform
-
Update the
specunderBuildConfigsection by changing the output to kindDockerImageand adding apushSecretspec: nodeSelector: null output: to: kind: DockerImage name: '<REGISTRY_URL>/<REGISTRY_NAMESPACE>/openshiftapp:latest' pushSecret: name: push-secret
{:codeblock}
A build is the process of transforming input parameters into a resulting object. Most often, the process is used to transform input parameters or source code into a runnable image. A
BuildConfigobject is the definition of the entire build process. -
Search for
containersand update the image withcontainers: -image: '<REGISTRY_URL>/<REGISTRY_NAMESPACE>/openshiftapp:latest' name: openshiftapp
{:codeblock}
-
Save the YAML file.
{:#deploy_app_to_cluster} In this section, you will deploy the application to the cluster using the generated openshift.yaml file. Once deployed, you will access the application by creating a route. You will also learn how to automatically build and redeploy when the app is updated.
-
Before creating the app, you need to copy and patch the image-pull secret from the
defaultproject to your project(openshiftproject)oc get secret default-us-icr-io -n default -o yaml | sed 's/default/openshiftproject/g' | oc -n openshiftproject create -f -
{:pre}
If you are using {{site.data.keyword.registryshort_notm}} from a region other than US, follow the instructions in this link to copy pull secrets. {:tip}
-
For the image pull secret to take effect, you need to add it in the
defaultservice accountoc secrets add serviceaccount/default secrets/openshiftproject-us-icr-io --for=pull
{:pre}
-
Create a new openshift app along with a buildconfig(bc), deploymentconfig(dc), service(svc), imagestream(is) using the updated yaml
oc create -f openshift.yaml
{:pre}
To learn about the core concepts of {{site.data.keyword.openshiftshort}}, refer this link {:tip}
-
To check the builder Docker image creation and pushing to the {{site.data.keyword.registryshort_notm}}, run the below command
oc logs -f bc/openshiftapp
{:pre}
-
You can check the status of deployment and service using
oc status
{:pre}
To access the app, you need to create a route. A route announces your service to the world.
- Create a route by running the below command in a terminal
{:pre}
oc expose service openshiftapp --port=3000
- You can access the app through IBM provided domain. Run the below command for the URL
{:pre}
oc get routes
- Copy the HOST/PORT value and paste the URL in a browser to see your app in action.
{: #secure_default_route}
- To create a secured HTTPS route encrypted with the default certificate for {{site.data.keyword.openshiftshort}}, you can use the
create routecommand.{:pre}oc create route edge openshifthttps --service=openshiftapp --port=3000
- For the HTTPS HOST URL, run
oc get routes. Copy and paste the URL with HTTPS(https://<HOST>) next to the route openshifthttps in a browser.
In this step, you will automate the build and deploy process. So that whenever you update the application and push the changes to the Private repo, a new build config is generated creating a build in turn generating a new version of the builder Docker image. This image will be deployed automatically.
-
You will create a new GitLab Webhook trigger. Webhook triggers allow you to trigger a new build by sending a request to the {{site.data.keyword.openshiftshort}} Container Platform API endpoint.You can define these triggers using GitHub, GitLab, Bitbucket, or Generic webhooks.
oc set triggers bc openshiftapp --from-gitlab{:pre}
-
To add a webhook on the GitLab repository, you need a URL and a secret
- For webhook GitLab URL,
{:pre}
oc describe bc openshiftapp | grep -A 1 "GitLab"
- For secret that needs to be passed in the webhook URL,
{:pre}
oc get bc openshiftapp -o yaml | grep -A 3 "\- gitlab"
- Replace
<secret>in the webhook GitLab URL with the secret value under gitlab in the above command output.
- For webhook GitLab URL,
-
Open your private git repo on a browser using the Git repo HTTPS link then click on Settings and click Integrations.
-
Paste the URL and click Add webhook. Test the URL by clicking Test and selecting Push events.
-
Update the ImagePolicy of the image stream to query {{site.data.keyword.registryshort_notm}} at a scheduled interval to synchronize tag and image metadata. This will update the
tagsdefinitionoc tag <REGISTRY_URL>/<REGISTRY_NAMESPACE>/openshiftapp:latest openshiftapp:latest --scheduled=true
{:pre}
-
Open the cloned repo in an IDE to update the
h1tag of local public/index.html file and change it to 'Congratulations! <YOUR_NAME>'. -
Save and push the code to the repo
git add public/index.html git commit -m "Updated with my name" git push -u origin master{:pre}
-
You can check the progress of the build and deploy with
oc statuscommand. Once the deployment is successful, refresh the route HOST address to see the updated web app.Sometimes, the deployment may take up to 15 minutes to import the latest image stream. You can either wait or manually import using
oc import-image openshiftappcommand. Refer this link for more info. {:tip}
{: #custom_domain}
To use your custom domain, you need to update your domain DNS records with a CNAME record pointing to your IBM-provided domain(route URL).
- Create a route exposing the service at a hostname by replacing
<HOSTNAME>with your hostname(e.g.,www.example.com), so that external clients can reach it by name.{:pre}oc expose svc/openshiftapp --hostname=<HOSTNAME> --name=openshiftappdomain --port=3000
- Access your application at
http://<customdomain>/
-
To create a secured HTTPS route, you can use your own certificate and key files from a CA like letsencrypt.org and pass them with the
create routecommandoc create route edge openshifthttpsca --service=openshiftapp --cert=example.pem --key=example.key --ca-cert=ca.pem --hostname=<www.HOSTNAME> --port=3000
{:pre}
Here, you have used Edge termination. To learn about other termination types like passthrough and re-encryption, refer secure routes {:tip}
{:#monitor_application}
In this section, you will learn to monitor the health and performance of your application. {{site.data.keyword.openshiftshort}} Container Platform ships with a pre-configured and self-updating monitoring stack that is based on the Prometheus open source project and its wider eco-system. It provides monitoring of cluster components and ships with a set of Grafana dashboards
- To access the web UIs of Prometheus and Grafana along with Alertmanager, run the below command and make sure to prepend
https://to the returned addresses(HOST). You cannot access web UIs using unencrypted connection.If prompted, click Login with OpenShift and authorize access by allowing selected permissions.{:pre}oc get routes -n openshift-monitoring
- You will use Apache ab to generate load on your deployed application by hitting the route URL 5000 times with 100 concurrent requests at a time. This will in turn generate data into Prometheus.
{:pre}
ab -n 5000 -c 100 <APPLICATION_ROUTE_URL>/
- In the expression box of Prometheus web UI, enter namespace_pod_name_container_name:container_cpu_usage_seconds_total:sum_rate{namespace="openshiftproject"} and click Execute to see the total container cpu usage in seconds on a Graph and a console.
- Open the Grafana web UI URL on a browser.
- On the Grafana Home page, click on K8s / Compute Resources / Pod and Select
- datasource: Prometheus
- namespace: openshiftproject
- pod: openshiftapp-DEPLOYMENT_NUMBER-POD_ID
- Check the CPU and memory usage.
- For logging, you can use the in-built
oc logscommand.
You can also provision and use {{site.data.keyword.la_full_notm}} and {{site.data.keyword.mon_full_notm}} services for logging and monitoring your {{site.data.keyword.openshiftshort}} application. Follow the instructions mentioned in this link to setup LogDNA and Sysdig add-ons to monitor cluster health. {:tip}
{:#scaling_app}
In this section, you will learn how to manually scale your application.
- You can achieve manual scaling of your pods with
oc scalecommand. The command sets a new size for a deployment or replication controller{:pre}oc scale dc openshiftapp --replicas=2
- You can see a new pod being provisionsed by running
oc get podscommand. - Rerun the Monitoring step to see the updated logs for both the pods.
{:#cleanup}
- Delete the cluster or only delete the {{site.data.keyword.openshiftshort}}(oc) artifacts created for the application if you plan to reuse the cluster.
- To delete all
openshiftappapplication resource objects, run the below command{:pre}oc delete all --selector app=openshiftapp
- To delete the project
{:pre}
oc delete project openshiftproject
