OpenShift - 快速入门



OpenShift 提供两种创建和部署应用程序的方式:图形用户界面 (GUI) 或命令行界面 (CLI)。本章将使用 CLI 创建一个新的应用程序。我们将使用 OC 客户端与 OpenShift 环境进行通信。

创建新的应用程序

在 OpenShift 中,有三种创建新应用程序的方法。

  • 从源代码
  • 从镜像
  • 从模板

从源代码

当我们尝试从源代码创建应用程序时,OpenShift 会查找存储库中存在的 Dockerfile,该文件定义应用程序的构建流程。我们将使用 `oc new-app` 命令创建应用程序。

使用存储库时,首先要记住的是,它应该指向存储库中的一个源,OpenShift 将从中拉取代码并进行构建。

如果存储库克隆在安装了 OC 客户端的 Docker 机器上,并且用户位于同一目录中,则可以使用以下命令创建它。

$ oc new-app . <Hear. Denotes current working directory>

以下是一个尝试从远程存储库的特定分支构建的示例。

$ oc new-app https://github.com/openshift/Testing-deployment.git#test1

这里,`test1` 是我们尝试在 OpenShift 中创建新应用程序的分支。

在指定存储库中的 Dockerfile 时,我们需要定义构建策略,如下所示。

$ oc new-app OpenShift/OpenShift-test~https://github.com/openshift/Testingdeployment.git

从镜像

使用镜像构建应用程序时,镜像存在于本地 Docker 服务器、内部托管的 Docker 存储库或 Docker Hub 上。用户只需确保可以无问题地从 Hub 拉取镜像。

OpenShift 能够确定使用的源,无论是 Docker 镜像还是源流。但是,如果用户希望,他可以明确定义它是镜像流还是 Docker 镜像。

$ oc new-app - - docker-image tomcat

使用镜像流 -

$ oc new-app tomcat:v1

从模板

模板可用于创建新的应用程序。它可以是已有的模板,也可以是新创建的模板。

下面的 yaml 文件基本上是一个可用于部署的模板。

apiVersion: v1
kind: Template
metadata:
   name: <Name of template>
   annotations:
      description: <Description of Tag>
      iconClass: "icon-redis"
      tags: <Tages of image>
objects:
   - apiVersion: v1
   kind: Pod
   metadata:
      name: <Object Specification>
spec:
   containers:
      image: <Image Name>
      name: master
      ports:
      - containerPort: <Container port number>
         protocol: <Protocol>
labels:
   redis: <Communication Type>

开发和部署 Web 应用程序

在 OpenShift 中开发新的应用程序

为了在 OpenShift 中创建一个新的应用程序,我们必须编写一个新的应用程序代码,并使用 OpenShift OC build 命令进行构建。如前所述,我们有多种创建新镜像的方法。在这里,我们将使用模板来构建应用程序。此模板将在使用 `oc new-app` 命令运行时构建一个新的应用程序。

以下模板将创建:两个前端应用程序和一个数据库。除此之外,它还将创建两个新服务,这些应用程序将被部署到 OpenShift 集群。在构建和部署应用程序时,我们首先需要在 OpenShift 中创建一个命名空间,并在该命名空间下部署应用程序。

创建一个新的命名空间

$ oc new-project openshift-test --display-name = "OpenShift 3 Sample" --
description = "This is an example project to demonstrate OpenShift v3"

模板

{
   "kind": "Template",
   "apiVersion": "v1",
   "metadata": {
      "name": "openshift-helloworld-sample",
      "creationTimestamp": null,
         "annotations": {
         "description": "This example shows how to create a simple openshift
         application in openshift origin v3",
         "iconClass": "icon-openshift",
         "tags": "instant-app,openshift,mysql"
      }
   }
},

对象定义

模板中的密钥定义

"objects": [
{
   "kind": "Secret",
   "apiVersion": "v1",
   "metadata": {"name": "dbsecret"},
   "stringData" : {
      "mysql-user" : "${MYSQL_USER}",
      "mysql-password" : "${MYSQL_PASSWORD}"
   }
},

模板中的服务定义

{
   "kind": "Service",
   "apiVersion": "v1",
   "metadata": {
      "name": "frontend",
      "creationTimestamp": null
   },
   "spec": {
      "ports": [
         {
            "name": "web",
            "protocol": "TCP",
            "port": 5432,
            "targetPort": 8080,
            "nodePort": 0
         }
      ],
      "selector": {"name": "frontend"},
      "type": "ClusterIP",
      "sessionAffinity": "None"
   },
   "status": {
      "loadBalancer": {}
   }
},

模板中的路由定义

{
   "kind": "Route",
   "apiVersion": "v1",
   "metadata": {
      "name": "route-edge",
      "creationTimestamp": null,
      "annotations": {
         "template.openshift.io/expose-uri": "http://{.spec.host}{.spec.path}"
      }
   },
   "spec": {
      "host": "www.example.com",
      "to": {
         "kind": "Service",
         "name": "frontend"
      },
      "tls": {
         "termination": "edge"
      }
   },
   "status": {}
},
{ 
   "kind": "ImageStream",
   "apiVersion": "v1",
   "metadata": {
      "name": "origin-openshift-sample",
      "creationTimestamp": null
   },
   "spec": {},
   "status": {
      "dockerImageRepository": ""
   }
},
{ 
   "kind": "ImageStream",
   "apiVersion": "v1",
   "metadata": {
      "name": "openshift-22-ubuntu7",
      "creationTimestamp": null 
   },
   "spec": {
      "dockerImageRepository": "ubuntu/openshift-22-ubuntu7"
   },
   "status": {
      "dockerImageRepository": ""
   }
},

模板中的构建配置定义

{
   "kind": "BuildConfig",
   "apiVersion": "v1",
   "metadata": {
      "name": "openshift-sample-build",
      "creationTimestamp": null,
      "labels": {name": "openshift-sample-build"}
   },
   "spec": {
      "triggers": [
         { "type": "GitHub",
            "github": {
            "secret": "secret101" } 
         },
         {
            "type": "Generic",
            "generic": {
               "secret": "secret101",
               "allowEnv": true } 
         },
         { 
            "type": "ImageChange",
            "imageChange": {} 
         },
         { "type": "ConfigChange”}
      ],
      "source": {
         "type": "Git",
         "git": {
            "uri": https://github.com/openshift/openshift-hello-world.git } 
      },
      "strategy": {
         "type": "Docker",
         "dockerStrategy": {
            "from": {
               "kind": "ImageStreamTag",
               "name": "openshift-22-ubuntu7:latest” 
            },
            "env": [
               {
                  "name": "EXAMPLE",
                  "value": "sample-app"
               }
            ]					
         }
      },
      "output": {
         "to": {
            "kind": "ImageStreamTag",
            "name": "origin-openshift-sample:latest"
         }
      },
      "postCommit": {
         "args": ["bundle", "exec", "rake", "test"]
      },
      "status": {
         "lastVersion": 0
      }
   }
},

部署配置定义

"status": {
   "lastVersion": 0
}
{
   "kind": "DeploymentConfig",
   "apiVersion": "v1",
   "metadata": {
      "name": "frontend",
      "creationTimestamp": null
   }
}, 
"spec": {
   "strategy": {
      "type": "Rolling",
      "rollingParams": {
         "updatePeriodSeconds": 1,
         "intervalSeconds": 1,
         "timeoutSeconds": 120,
         "pre": {
            "failurePolicy": "Abort",
            "execNewPod": {
               "command": [
                  "/bin/true"
               ],
               "env": [
                  { 
                     "name": "CUSTOM_VAR1",
                     "value": "custom_value1"
                  }
               ]						
            }
         }
      }
   }
}
"triggers": [
   {
      "type": "ImageChange",
      "imageChangeParams": {
         "automatic": true,
         "containerNames": [
            "openshift-helloworld"
         ],
         "from": {
            "kind": "ImageStreamTag",
            "name": "origin-openshift-sample:latest"
         }
      }
   },
   {
      "type": "ConfigChange"
   }
],
"replicas": 2,
"selector": {
   "name": "frontend"
},
"template": {
   "metadata": {
      "creationTimestamp": null,
      "labels": {
         "name": "frontend"
      }
   },
   "spec": {
      "containers": [
         {
            "name": "openshift-helloworld",
            "image": "origin-openshift-sample",
            "ports": [
               { 
                  "containerPort": 8080,
                  "protocol": "TCP” 
               }
            ],
            "env": [
               {
                  "name": "MYSQL_USER",
                  "valueFrom": {
                     "secretKeyRef" : {
                        "name" : "dbsecret",
                        "key" : "mysql-user"
                     }
                  }
               },
               {
                  "name": "MYSQL_PASSWORD",
                  "valueFrom": {
                     "secretKeyRef" : {
                        "name" : "dbsecret",
                        "key" : "mysql-password"
                     }
                  }
               },
               {
                  "name": "MYSQL_DATABASE",
                  "value": "${MYSQL_DATABASE}"
               }
            ],
            "resources": {},
            "terminationMessagePath": "/dev/termination-log",
            "imagePullPolicy": "IfNotPresent",
            "securityContext": {
               "capabilities": {},
               "privileged": false
            }
         }
      ],
      "restartPolicy": "Always",
      "dnsPolicy": "ClusterFirst"
   },
   "status": {}
},

模板中的服务定义

{
   "kind": "Service",
   "apiVersion": "v1",
   "metadata": {
      "name": "database",
      "creationTimestamp": null 
   },
   "spec": {
   "ports": [
      {
         "name": "db",
         "protocol": "TCP",
         "port": 5434,
         "targetPort": 3306,
         "nodePort": 0
      } 
   ],
   "selector": {
      "name": "database 
   },
   "type": "ClusterIP",
   "sessionAffinity": "None" },
   "status": {
      "loadBalancer": {}
   }
},

模板中的部署配置定义

{
   "kind": "DeploymentConfig",
   "apiVersion": "v1",
   "metadata": {
      "name": "database",
      "creationTimestamp": null
   },
   "spec": {
      "strategy": {
         "type": "Recreate",
         "resources": {}
      },
      "triggers": [
         {
            "type": "ConfigChange"
         }
      ],
      "replicas": 1,
      "selector": {"name": "database"},
      "template": {
         "metadata": {
            "creationTimestamp": null,
            "labels": {"name": "database"}
         },
         "template": {
            "metadata": {
               "creationTimestamp": null,
               "labels": {
                  "name": "database"
               } 
            },
            "spec": {
               "containers": [
                  {
                     "name": "openshift-helloworld-database",
                     "image": "ubuntu/mysql-57-ubuntu7:latest",
                     "ports": [
                        {
                           "containerPort": 3306,
                           "protocol": "TCP" 
                        }
                     ],
                     "env": [
                        {
                           "name": "MYSQL_USER",
                           "valueFrom": {
                              "secretKeyRef" : {
                                 "name" : "dbsecret",
                                 "key" : "mysql-user"
                              }
                           }
                        },
                        {
                           "name": "MYSQL_PASSWORD",
                           "valueFrom": {
                              "secretKeyRef" : {
                                 "name" : "dbsecret",
                                 "key" : "mysql-password"
                              }
                           }
                        },
                        {
                           "name": "MYSQL_DATABASE",
                           "value": "${MYSQL_DATABASE}" 
                        } 
                     ],
                     "resources": {},
                     "volumeMounts": [
                        {
                           "name": "openshift-helloworld-data",
                           "mountPath": "/var/lib/mysql/data"
                        }
                     ],
                     "terminationMessagePath": "/dev/termination-log",
                     "imagePullPolicy": "Always",
                     "securityContext": {
                        "capabilities": {},
                        "privileged": false
                     } 
                  }
               ],
               "volumes": [
                  { 
                     "name": "openshift-helloworld-data",
                     "emptyDir": {"medium": ""} 
                  } 
               ],
               "restartPolicy": "Always",
               "dnsPolicy": "ClusterFirst” 
            } 
         }
      },
      "status": {} 
   },
   "parameters": [
      { 
         "name": "MYSQL_USER",
         "description": "database username",
         "generate": "expression",
         "from": "user[A-Z0-9]{3}",
         "required": true 
      },
      {
         "name": "MYSQL_PASSWORD",
         "description": "database password",
         "generate": "expression",
         "from": "[a-zA-Z0-9]{8}",
         "required": true
      }, 
      {
         "name": "MYSQL_DATABASE",
         "description": "database name",
         "value": "root",
         "required": true 
      } 
   ],
   "labels": {
      "template": "application-template-dockerbuild" 
   } 
}

上述模板文件需要一次性编译。我们需要首先将所有内容复制到单个文件中,并在完成后将其命名为 yaml 文件。

我们需要运行以下命令来创建应用程序。

$ oc new-app application-template-stibuild.json
--> Deploying template openshift-helloworld-sample for "application-template-stibuild.json"

   openshift-helloworld-sample
   ---------
   This example shows how to create a simple ruby application in openshift origin v3
   * With parameters:
      * MYSQL_USER = userPJJ # generated
      * MYSQL_PASSWORD = cJHNK3se # generated
      * MYSQL_DATABASE = root

--> Creating resources with label app = ruby-helloworld-sample ...
   service "frontend" created
   route "route-edge" created
   imagestream "origin-ruby-sample" created
   imagestream "ruby-22-centos7" created
   buildconfig "ruby-sample-build" created
   deploymentconfig "frontend" created
   service "database" created
   deploymentconfig "database" created
   
--> Success
   Build scheduled, use 'oc logs -f bc/ruby-sample-build' to track its progress.
   Run 'oc status' to view your app.

如果我们希望监控构建过程,可以使用 -

$ oc get builds

NAME                        TYPE      FROM          STATUS     STARTED         DURATION
openshift-sample-build-1    Source   Git@bd94cbb    Running    7 seconds ago   7s

我们可以使用以下命令检查 OpenShift 上已部署的应用程序 -

$ oc get pods
NAME                            READY   STATUS      RESTARTS   AGE
database-1-le4wx                1/1     Running     0          1m
frontend-1-e572n                1/1     Running     0          27s
frontend-1-votq4                1/1     Running     0          31s
opeshift-sample-build-1-build   0/1     Completed   0          1m

我们可以使用以下命令检查应用程序服务是否根据服务定义创建 -

$ oc get services
NAME        CLUSTER-IP      EXTERNAL-IP     PORT(S)      SELECTOR          AGE
database    172.30.80.39    <none>         5434/TCP     name=database      1m
frontend    172.30.17.4     <none>         5432/TCP     name=frontend      1m
广告