OCP使用CLI创建和构建应用

文章目录

环境

  • RHEL 9.3
  • Red Hat OpenShift Local 2.32

登录

通过 crc console --credentials 可以查看登录信息:

powershell 复制代码
$ crc console --credentials
To login as a regular user, run 'oc login -u developer -p developer https://api.crc.testing:6443'.
To login as an admin, run 'oc login -u kubeadmin -p 9cdKu-ihELt-PYiiN-aazX2 https://api.crc.testing:6443'

登录:

powershell 复制代码
$ oc login -u kubeadmin -p 9cdKu-ihELt-PYiiN-aazX2 https://api.crc.testing:6443
Login successful.

You have access to 66 projects, the list has been suppressed. You can list all projects with 'oc projects'

Using project "default".

注: https://api.crc.testing:6443 是可选的,缺省就是登录本机。

查看当前身份:

powershell 复制代码
$ oc whoami
kubeadmin

登录时,可以加上 --web 选项,启动web console,通过web console登录:

powershell 复制代码
$ oc login --web
Opening login URL in the default browser: https://oauth-openshift.apps-crc.testing/oauth/authorize?client_id=openshift-cli-client&code_challenge=FXeS7NXkkgk-c8T2IBC62OerE5idgtetRqackO6n15E&code_challenge_method=S256&redirect_uri=http%3A%2F%2F127.0.0.1%3A35445%2Fcallback&response_type=code

创建project

Project使得用户社区可以在隔离中组织和管理其内容。Project是OCP对Kubernetes namespace的扩展。Project具有额外的功能,使得用户能够自我provision(self-provisioning)。

用户需要从管理员处接收project的访问权限。集群管理员可以允许开发人员创建自己的project。多数情况下,用户会自动获得其自己的project的访问权限。

每个project都有自己的一系列对象、策略、约束和service帐户。

创建project user-getting-started

powershell 复制代码
$ oc new-project user-getting-started --display-name="Getting Started with OpenShift"
Now using project "user-getting-started" on server "https://api.crc.testing:6443".

You can add applications to this project with the 'new-app' command. For example, try:

    oc new-app rails-postgresql-example

to build a new example application in Ruby. Or use kubectl to deploy a simple Kubernetes application:

    kubectl create deployment hello-node --image=registry.k8s.io/e2e-test-images/agnhost:2.43 -- /agnhost serve-hostname

创建project后,会自动切换到该project。

赋予查看权限

OCP会在每个project中自动创建一些特殊的service帐户。默认服务帐户会负责运行pod。OCP使用并将此service帐户注入到所启动的每个pod中。

本例为默认的 ServiceAccount 对象创建一个 RoleBinding 对象。Service帐户与 OCP API通信,以了解project中的 pod、service和资源。

将查看(view)角色添加到 user-get-started project中的默认service帐户:

powershell 复制代码
$ oc adm policy add-role-to-user view -z default -n user-getting-started
clusterrole.rbac.authorization.k8s.io/view added: "default"

部署第一个image

在OCP中部署应用的最简单方法是运行已有的容器image。本例部署一个应用的前端组件,名为 national-parks-app 。该web应用显示一个交互式的地图,显示全球主要国家公园的位置。

powershell 复制代码
$ oc new-app quay.io/openshiftroadshow/parksmap:latest --name=parksmap -l 'app=national-parks-app,component=parksmap,role=frontend,app.kubernetes.io/part-of=national-parks-app'
--> Found container image 0c2f55f (3 years old) from quay.io for "quay.io/openshiftroadshow/parksmap:latest"

    * An image stream tag will be created as "parksmap:latest" that will track this image

--> Creating resources with label app=national-parks-app,app.kubernetes.io/part-of=national-parks-app,component=parksmap,role=frontend ...
    imagestream.image.openshift.io "parksmap" created
    deployment.apps "parksmap" created
    service "parksmap" 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/parksmap' 
    Run 'oc status' to view your app.

创建route

外部客户端可以通过路由层访问OCP里运行的应用,该路由层后端的数据对象被称为route。默认的OCP路由器(HAProxy)使用传入请求的HTTP header来确定代理连接的位置。

也可以为route定义安全性,比如TLS。

查看service:

powershell 复制代码
$ oc get service
NAME       TYPE        CLUSTER-IP    EXTERNAL-IP   PORT(S)    AGE
parksmap   ClusterIP   10.217.4.38   <none>        8080/TCP   6m11s

注:我使用的是Red Hat OpenShift Local,所以没有 EXTERNAL-IP

创建route:

powershell 复制代码
$ oc create route edge parksmap --service=parksmap
route.route.openshift.io/parksmap created

查看route:

powershell 复制代码
$ oc get route
NAME       HOST/PORT                                        PATH   SERVICES   PORT       TERMINATION   WILDCARD
parksmap   parksmap-user-getting-started.apps-crc.testing          parksmap   8080-tcp   edge          None

检查pod

OCP使用Kubernetes的pod概念,它是部署在同一主机上的一个或多个容器,也是可被定义、部署和管理的最小计算单元。对于容器来说,pod大致相当于机器实例(物理的或虚拟的)。

可以查看集群中的pod,并确定这些pod以及整个集群的健康状态。

powershell 复制代码
$ oc get pod
NAME                       READY   STATUS    RESTARTS   AGE
parksmap-69b46d5f7-glwd2   1/1     Running   0          14m

查看pod详细信息:

powershell 复制代码
$ oc describe pod
Name:             parksmap-69b46d5f7-glwd2
Namespace:        user-getting-started
Priority:         0
Service Account:  default
Node:             crc-ksq4m-master-0/192.168.126.11
Start Time:       Fri, 09 Feb 2024 08:09:58 +0800
Labels:           app=national-parks-app
                  app.kubernetes.io/part-of=national-parks-app
                  component=parksmap
                  deployment=parksmap
                  pod-template-hash=69b46d5f7
                  role=frontend
Annotations:      k8s.v1.cni.cncf.io/network-status:
                    [{
                        "name": "openshift-sdn",
                        "interface": "eth0",
                        "ips": [
                            "10.217.0.65"
                        ],
                        "default": true,
                        "dns": {}
                    }]
                  openshift.io/generated-by: OpenShiftNewApp
                  openshift.io/scc: restricted-v2
                  seccomp.security.alpha.kubernetes.io/pod: runtime/default
Status:           Running
SeccompProfile:   RuntimeDefault
IP:               10.217.0.65
IPs:
  IP:           10.217.0.65
Controlled By:  ReplicaSet/parksmap-69b46d5f7
Containers:
  parksmap:
    Container ID:   cri-o://36d858cc571f219418f2d5fefcd4ebd606611c51a57f779c26fa6d3f86559f03
    Image:          quay.io/openshiftroadshow/parksmap@sha256:89d1e324846cb431df9039e1a7fd0ed2ba0c51aafbae73f2abd70a83d5fa173b
    Image ID:       quay.io/openshiftroadshow/parksmap@sha256:89d1e324846cb431df9039e1a7fd0ed2ba0c51aafbae73f2abd70a83d5fa173b
    Port:           8080/TCP
    Host Port:      0/TCP
    State:          Running
      Started:      Fri, 09 Feb 2024 08:10:34 +0800
    Ready:          True
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-92x92 (ro)
Conditions:
  Type              Status
  Initialized       True 
  Ready             True 
  ContainersReady   True 
  PodScheduled      True 
Volumes:
  kube-api-access-92x92:
    Type:                    Projected (a volume that contains injected data from multiple sources)
    TokenExpirationSeconds:  3607
    ConfigMapName:           kube-root-ca.crt
    ConfigMapOptional:       <nil>
    DownwardAPI:             true
    ConfigMapName:           openshift-service-ca.crt
    ConfigMapOptional:       <nil>
QoS Class:                   BestEffort
Node-Selectors:              <none>
Tolerations:                 node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
                             node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events:
  Type    Reason          Age   From               Message
  ----    ------          ----  ----               -------
  Normal  Scheduled       15m   default-scheduler  Successfully assigned user-getting-started/parksmap-69b46d5f7-glwd2 to crc-ksq4m-master-0
  Normal  AddedInterface  15m   multus             Add eth0 [10.217.0.65/23] from openshift-sdn
  Normal  Pulling         15m   kubelet            Pulling image "quay.io/openshiftroadshow/parksmap@sha256:89d1e324846cb431df9039e1a7fd0ed2ba0c51aafbae73f2abd70a83d5fa173b"
  Normal  Pulled          14m   kubelet            Successfully pulled image "quay.io/openshiftroadshow/parksmap@sha256:89d1e324846cb431df9039e1a7fd0ed2ba0c51aafbae73f2abd70a83d5fa173b" in 34.192111778s (34.19212265s including waiting)
  Normal  Created         14m   kubelet            Created container parksmap
  Normal  Started         14m   kubelet            Started container parksmap

注:也可以 oc describe pod xxx 查看某个pod的详细信息。本例中在当前project里只有一个pod,所以二者效果都一样。

扩展应用

在Kubernetes中, Deployment 对象定义了如何部署应用。多数情况下,用户会把pod、service、ReplicaSets、deployment资源一起使用。在大多数情况下,OCP会创建这些资源。

在部署 national-parks-app image时,会创建一个deployment资源。本例只部署了一个pod。

把应用从一个pod实例扩展到两个pod实例:

powershell 复制代码
$ oc scale --current-replicas=1 --replicas=2 deployment/parksmap
deployment.apps/parksmap scaled

查看pod:

powershell 复制代码
$ oc get pods
NAME                       READY   STATUS    RESTARTS   AGE
parksmap-69b46d5f7-btk54   1/1     Running   0          33s
parksmap-69b46d5f7-glwd2   1/1     Running   0          22m

把应用缩减回一个pod实例:

powershell 复制代码
$ oc scale --current-replicas=2 --replicas=1 deployment/parksmap
deployment.apps/parksmap scaled

查看pod:

powershell 复制代码
$ oc get pods
NAME                       READY   STATUS    RESTARTS   AGE
parksmap-69b46d5f7-glwd2   1/1     Running   0          24m

部署一个Python应用

本例为 parksmap 应用部署后端service。Python应用在MongoDB数据库执行2D地理空间( geo-spatial)查询,以定位和返回世界上所有国家公园的地图坐标。

部署的后端service是 nationalparks

创建Python应用:

powershell 复制代码
$ oc new-app python~https://github.com/openshift-roadshow/nationalparks-py.git --name nationalparks -l 'app=national-parks-app,component=nationalparks,role=backend,app.kubernetes.io/part-of=national-parks-app,app.kubernetes.io/name=python' --allow-missing-images=true
warning: Cannot check if git requires authentication.
--> Found image 3c5d265 (5 weeks old) in image stream "openshift/python" under tag "3.9-ubi8" for "python"

    Python 3.9 
    ---------- 
    Python 3.9 available as container is a base platform for building and running various Python 3.9 applications and frameworks. Python is an easy to learn, powerful programming language. It has efficient high-level data structures and a simple but effective approach to object-oriented programming. Python's elegant syntax and dynamic typing, together with its interpreted nature, make it an ideal language for scripting and rapid application development in many areas on most platforms.

    Tags: builder, python, python39, python-39, rh-python39

    * A source build using source code from https://github.com/openshift-roadshow/nationalparks-py.git will be created
      * The resulting image will be pushed to image stream tag "nationalparks:latest"
      * Use 'oc start-build' to trigger a new build

--> Creating resources with label app=national-parks-app,app.kubernetes.io/name=python,app.kubernetes.io/part-of=national-parks-app,component=nationalparks,role=backend ...
    imagestream.image.openshift.io "nationalparks" created
    buildconfig.build.openshift.io "nationalparks" created
    deployment.apps "nationalparks" created
    service "nationalparks" created
--> Success
    Build scheduled, use 'oc logs -f buildconfig/nationalparks' 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/nationalparks' 
    Run 'oc status' to view your app.

创建route来暴露 nationalparks 应用:

powershell 复制代码
$ oc create route edge nationalparks --service=nationalparks
route.route.openshift.io/nationalparks created

查看route:

powershell 复制代码
$ oc get route
NAME            HOST/PORT                                             PATH   SERVICES        PORT       TERMINATION   WILDCARD
nationalparks   nationalparks-user-getting-started.apps-crc.testing          nationalparks   8080-tcp   edge          None
parksmap        parksmap-user-getting-started.apps-crc.testing               parksmap        8080-tcp   edge          None

连接数据库

接下来,部署并连接一个MongoDB数据库, national -parks-app 应用将会存储位置信息于该数据库。一旦把 national-parks-app 应用标记为地图可视化工具的后端, parksmap deployment会使用OCP发现机制来自动显示地图。

连接数据库:

powershell 复制代码
$ oc new-app quay.io/centos7/mongodb-36-centos7 --name mongodb-nationalparks -e MONGODB_USER=mongodb -e MONGODB_PASSWORD=mongodb -e MONGODB_DATABASE=mongodb -e MONGODB_ADMIN_PASSWORD=mongodb -l 'app.kubernetes.io/part-of=national-parks-app,app.kubernetes.io/name=mongodb'
--> Found container image dc18f52 (2 years old) from quay.io for "quay.io/centos7/mongodb-36-centos7"

    MongoDB 3.6 
    ----------- 
    MongoDB (from humongous) is a free and open-source cross-platform document-oriented database program. Classified as a NoSQL database program, MongoDB uses JSON-like documents with schemas. This container image contains programs to run mongod server.

    Tags: database, mongodb, rh-mongodb36

    * An image stream tag will be created as "mongodb-nationalparks:latest" that will track this image

--> Creating resources with label app.kubernetes.io/name=mongodb,app.kubernetes.io/part-of=national-parks-app ...
    imagestream.image.openshift.io "mongodb-nationalparks" created
    deployment.apps "mongodb-nationalparks" created
    service "mongodb-nationalparks" 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-nationalparks' 
    Run 'oc status' to view your app.

创建secret

Secret 对象提供了一种机制来保存敏感信息,如密码、OCP客户端配置文件、私有源仓库凭证等。Secret把敏感内容与pod解耦。可以通过volume插件把secret mount到容器中,系统也可以为pod而使用secret执行操作。本例添加secret nationalparks-mongodb-parameters ,并将它mount到 nationalparks 工作负载中。

创建secret:

powershell 复制代码
$ oc create secret generic nationalparks-mongodb-parameters --from-literal=DATABASE_SERVICE_NAME=mongodb-nationalparks --from-literal=MONGODB_USER=mongodb --from-literal=MONGODB_PASSWORD=mongodb --from-literal=MONGODB_DATABASE=mongodb --from-literal=MONGODB_ADMIN_PASSWORD=mongodb
secret/nationalparks-mongodb-parameters created

更新环境变量,把mongodb secret 附加到 nationalpartks 工作负载:

powershell 复制代码
$ oc set env --from=secret/nationalparks-mongodb-parameters deploy/nationalparks
deployment.apps/nationalparks updated

显示 nationalpartks deployment的状态:

powershell 复制代码
$ oc rollout status deployment nationalparks
deployment "nationalparks" successfully rolled out

显示 mongodb-nationalparks deployment的状态:

powershell 复制代码
$ oc rollout status deployment mongodb-nationalparks
deployment "mongodb-nationalparks" successfully rolled out

直接看当前project里所有deployment的更新状态:

powershell 复制代码
$ oc rollout status deployment
deployment "mongodb-nationalparks" successfully rolled out
deployment "nationalparks" successfully rolled out
deployment "parksmap" successfully rolled out

加载数据并显示国家公园地图

目前已经部署了 parksmapNationalparks 应用,然后部署了 mongodb-nationalparks 数据库。但是,还没有把数据加载到数据库中。

加载国家公园数据:

powershell 复制代码
$ oc exec $(oc get pods -l component=nationalparks | tail -n 1 | awk '{print $1;}') -- curl -s http://localhost:8080/ws/data/load
"Items inserted in database: 2893"

验证:

powershell 复制代码
$ oc exec $(oc get pods -l component=nationalparks | tail -n 1 | awk '{print $1;}') -- curl -s http://localhost:8080/ws/data/all | jq .
[
  {
    "id": "Arikok National Park",
    "latitude": "12.489967",
    "longitude": "-69.9273915",
    "name": "Arikok National Park"
  },
  {
    "id": "Wakhan National Park",
    "latitude": "36.845432",
    "longitude": "72.28375",
    "name": "Wakhan National Park"
  },
......
......
  {
    "id": "Great Zimbabwe",
    "latitude": "-20.2674635",
    "longitude": "30.9337986",
    "name": "Great Zimbabwe"
  }
]

为route添加label:

powershell 复制代码
$ oc label route nationalparks type=parksmap-backend
route.route.openshift.io/nationalparks labeled

查看route:

powershell 复制代码
$ oc get routes
NAME            HOST/PORT                                             PATH   SERVICES        PORT       TERMINATION   WILDCARD
nationalparks   nationalparks-user-getting-started.apps-crc.testing          nationalparks   8080-tcp   edge          None
parksmap        parksmap-user-getting-started.apps-crc.testing               parksmap        8080-tcp   edge          None

打开浏览器,访问 https://parksmap-user-getting-started.apps-crc.testing ,如下:

清理

powershell 复制代码
crc delete -f

参考

  • https://access.redhat.com/documentation/en-us/openshift_container_platform/4.14/html-single/getting_started/index#openshift-cli
相关推荐
dawnsky.liu14 天前
红帽 Quay- 配置镜像代理缓存
kubernetes·openshift
ghostwritten1 个月前
openshift node NotReady & kubelet http: TLS handshake error
http·openshift·kubelet
solinger2 个月前
kubebuiler安装
kubernetes·openshift·ocp
-风中叮铃-4 个月前
OCP-042之:Oracle网络服务
数据库·oracle·ocp·网络服务
杭州云贝数据5 个月前
云贝教育 |【直播课】5月19日Oracle 19c OCM认证大师课 即将上课了!(附课件预览)
数据库·oracle·ocp
YUNBEE_chen5 个月前
Oracle 19c OCM考试难度如何?
数据库·oracle·ocp·ocm·19c ocm·19c ocp·ocm考试
十八年后又是一条好汉5 个月前
OCP Java17 SE Developers 复习题15(完)
java·ocp
dawnsky.liu5 个月前
OpenShift 4 - 了解 OpenShift 是如何使用节点本地镜像缓存
云原生·openshift·devops
浩澜大大6 个月前
openshift和k8s的差别
容器·kubernetes·openshift
腾科教育6 个月前
ocp考试是中文还是英文?ocp认证好考吗
oracle·ocp·ocm