OCP使用CLI创建和构建应用

文章目录

  • 环境
  • 登录
  • 创建project
  • 赋予查看权限
  • 部署第一个image
    • 创建route
    • 检查pod
    • 扩展应用
  • 部署一个Python应用
  • 连接数据库
    • 创建secret
    • 加载数据并显示国家公园地图
  • 清理
  • 参考

环境

  • RHEL 9.3
  • Red Hat OpenShift Local 2.32

登录

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

$ 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'

登录:

$ 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 是可选的,缺省就是登录本机。

查看当前身份:

$ oc whoami
kubeadmin

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

$ 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

$ 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-exampleto 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帐户:

$ 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应用显示一个交互式的地图,显示全球主要国家公园的位置。

$ 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" createddeployment.apps "parksmap" createdservice "parksmap" created
--> SuccessApplication 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:

$ 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:

$ oc create route edge parksmap --service=parksmap
route.route.openshift.io/parksmap created

查看route:

$ 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以及整个集群的健康状态。

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

查看pod详细信息:

$ 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-appapp.kubernetes.io/part-of=national-parks-appcomponent=parksmapdeployment=parksmappod-template-hash=69b46d5f7role=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: OpenShiftNewAppopenshift.io/scc: restricted-v2seccomp.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://36d858cc571f219418f2d5fefcd4ebd606611c51a57f779c26fa6d3f86559f03Image:          quay.io/openshiftroadshow/parksmap@sha256:89d1e324846cb431df9039e1a7fd0ed2ba0c51aafbae73f2abd70a83d5fa173bImage ID:       quay.io/openshiftroadshow/parksmap@sha256:89d1e324846cb431df9039e1a7fd0ed2ba0c51aafbae73f2abd70a83d5fa173bPort:           8080/TCPHost Port:      0/TCPState:          RunningStarted:      Fri, 09 Feb 2024 08:10:34 +0800Ready:          TrueRestart Count:  0Environment:    <none>Mounts:/var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-92x92 (ro)
Conditions:Type              StatusInitialized       True Ready             True ContainersReady   True PodScheduled      True 
Volumes:kube-api-access-92x92:Type:                    Projected (a volume that contains injected data from multiple sources)TokenExpirationSeconds:  3607ConfigMapName:           kube-root-ca.crtConfigMapOptional:       <nil>DownwardAPI:             trueConfigMapName:           openshift-service-ca.crtConfigMapOptional:       <nil>
QoS Class:                   BestEffort
Node-Selectors:              <none>
Tolerations:                 node.kubernetes.io/not-ready:NoExecute op=Exists for 300snode.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-0Normal  AddedInterface  15m   multus             Add eth0 [10.217.0.65/23] from openshift-sdnNormal  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 parksmapNormal  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实例:

$ oc scale --current-replicas=1 --replicas=2 deployment/parksmap
deployment.apps/parksmap scaled

查看pod:

$ 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实例:

$ oc scale --current-replicas=2 --replicas=1 deployment/parksmap
deployment.apps/parksmap scaled

查看pod:

$ 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应用:

$ 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" createdbuildconfig.build.openshift.io "nationalparks" createddeployment.apps "nationalparks" createdservice "nationalparks" created
--> SuccessBuild 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 应用:

$ oc create route edge nationalparks --service=nationalparks
route.route.openshift.io/nationalparks created

查看route:

$ 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发现机制来自动显示地图。

连接数据库:

$ 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" createddeployment.apps "mongodb-nationalparks" createdservice "mongodb-nationalparks" created
--> SuccessApplication 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:

$ 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 工作负载:

$ oc set env --from=secret/nationalparks-mongodb-parameters deploy/nationalparks
deployment.apps/nationalparks updated

显示 nationalpartks deployment的状态:

$ oc rollout status deployment nationalparks
deployment "nationalparks" successfully rolled out

显示 mongodb-nationalparks deployment的状态:

$ oc rollout status deployment mongodb-nationalparks
deployment "mongodb-nationalparks" successfully rolled out

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

$ oc rollout status deployment
deployment "mongodb-nationalparks" successfully rolled out
deployment "nationalparks" successfully rolled out
deployment "parksmap" successfully rolled out

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

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

加载国家公园数据:

$ 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"

验证:

$ 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:

$ oc label route nationalparks type=parksmap-backend
route.route.openshift.io/nationalparks labeled

查看route:

$ 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 ,如下:

在这里插入图片描述

清理

crc delete -f

参考

  • https://access.redhat.com/documentation/en-us/openshift_container_platform/4.14/html-single/getting_started/index#openshift-cli

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/462015.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

云游戏发行需要哪些条件

云游戏是一种创新性的游戏服务模式&#xff0c;将游戏运算和渲染等处理任务移至云端服务器&#xff0c;通过互联网实时传输画面和操作指令&#xff0c;使玩家能够在低端终端设备上也能流畅玩游戏。要做云游戏发行&#xff0c;需要考虑一系列条件&#xff0c;包括技术、基础设施…

猫头虎分享已解决Bug :内存泄漏(Memory Leak)

博主猫头虎的技术世界 &#x1f31f; 欢迎来到猫头虎的博客 — 探索技术的无限可能&#xff01; 专栏链接&#xff1a; &#x1f517; 精选专栏&#xff1a; 《面试题大全》 — 面试准备的宝典&#xff01;《IDEA开发秘籍》 — 提升你的IDEA技能&#xff01;《100天精通鸿蒙》 …

Go语言的100个错误使用场景(30-40)|数据类型与字符串使用

前言 大家好&#xff0c;这里是白泽。 《Go语言的100个错误以及如何避免》 是最近朋友推荐我阅读的书籍&#xff0c;我初步浏览之后&#xff0c;大为惊喜。就像这书中第一章的标题说到的&#xff1a;“Go: Simple to learn but hard to master”&#xff0c;整本书通过分析100…

小白都能看懂的力扣算法详解——链表(二)

LC 24.两两交换链表中的节点 题目描述&#xff1a;给你一个链表&#xff0c;两两交换其中相邻的节点&#xff0c;并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题&#xff08;即&#xff0c;只能进行节点交换&#xff09;。 24. 两两交换链表中的节点 -…

TCP 传输控制协议——详细

目录 1 TCP 1.1 TCP 最主要的特点 1.2 TCP 的连接 TCP 连接&#xff0c;IP 地址&#xff0c;套接字 1.3 可靠传输的工作原理 1.3.1 停止等待协议 &#xff08;1&#xff09;无差错情况 &#xff08;2&#xff09;出现差错 &#xff08;3&#xff09;确认丢失和确认迟到…

SECS/GEM300需要实现哪些内容

GEM300实现设备全自动化&#xff0c;也是金南瓜已经全面支持功能&#xff0c;作为国内首家和最好的300mm标准软件。 GEM300包含E4、E5、E30、E37、E39、E40、E84、E87、E90、E94、E116等 CJob全称Conrtol Job 1. 控制设备作业的控制 2. 包括队列、开始、暂停、继续、完成等等…

Mac使用AccessClient打开Linux堡垒机跳转闪退问题解决

登录公司的服务器需要使用到堡垒机&#xff0c;但是mac使用AccessClient登录会出现问题 最基础的AccessClient配置 AccessClient启动需要设置目录权限&#xff0c;可以直接设置为 权限 777 chmod 777 /Applications/AccessClient.app注: 如果不是这个路径,可以打开终端,将访达中…

探索设计模式的魅力:代理模式揭秘-软件世界的“幕后黑手”

设计模式专栏&#xff1a;http://t.csdnimg.cn/U54zu 目录 引言 一、魔法世界 1.1 定义与核心思想 1.2 静态代理 1.3 动态代理 1.4 虚拟代理 1.5 代理模式结构图 1.6 实例展示如何工作&#xff08;场景案例&#xff09; 不使用模式实现 有何问题 使用模式重构示例 二、…

FPGA开发

Quartus13.0使用 编译下载&#xff1a; 添加引脚&#xff1a; # ---------------- LED ---------------- # set_location_assignment PIN_K2 -to led_out[11] set_location_assignment PIN_J1 -to led_out[10] set_location_assignment PIN_J2 -to led_out[9] set_locatio…

Web课程学习笔记--JavaScript操作DOM常用的API

JavaScript操作DOM常用的API 1 什么是DOM 文档对象模型 (DOM) 是HTML和XML文档的编程接口。它提供了对文档的结构化的表述&#xff0c;并定义了一种方式可以使从程序中对该结构进行访问&#xff0c;从而改变文档的结构&#xff0c;样式和内容。 文档对象模型 (DOM) 是对HTML文…

RK3568平台 Regmap子系统

一.Regmap API 简介 Linux 下使用 i2c_transfer 来读写 I2C 设备中的寄存器&#xff0c;SPI 接口的话使用 spi_write/spi_read 等。I2C/SPI 芯片又非常的多&#xff0c;因此 Linux 内核里面就会充斥了大量的 i2c_transfer 这类的冗余 代码&#xff0c;再者&#xff0c;代码的复…

那些 C语言指针 你不知道的小秘密 (3)

本篇会加入个人的所谓‘鱼式疯言’ ❤️❤️❤️鱼式疯言:❤️❤️❤️此疯言非彼疯言 而是理解过并总结出来通俗易懂的大白话, 我会尽可能的在每个概念后插入鱼式疯言,帮助大家理解的. &#x1f92d;&#x1f92d;&#x1f92d;可能说的不是那么严谨.但小编初心是能让更多人能…