OpenShift - 入门

OpenShift包含两种类型的中位数,可通过GUI或CLI创建和部署应用程序.在本章中,我们将使用CLI来创建新的应用程序.我们将使用OC客户端与OpenShift环境进行通信.

创建新应用程序

在OpenShift中,有三种创建新方法的方法申请.

  • 来自源代码

  • 来自图片

  • 来自模板

来自源代码

当我们尝试从中创建应用程序时源代码,OpenShift查找应该存在于repo中的Docker文件,该文件定义了应用程序构建流程.我们将使用oc new-app来创建一个应用程序.

使用repo时要记住的第一件事是,它应该指向来自OpenShift将拉动的repo中的原点代码并构建它.

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

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

以下是尝试从特定分支的远程仓库进行构建的示例.

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

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

在存储库中指定Docker文件时,我们需要定义构建策略,如下所示.

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

从图像

使用图像构建应用程序时,图像存在于本地Docker服务器,内部托管的Docker存储库中,或者Docker中心.用户唯一需要确保的是,他有权从集线器中提取图像而没有任何问题.

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构建命令构建它.如上所述,我们有多种创建新图像的方法.在这里,我们将使用模板来构建应用程序.当使用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