OpenShift

关于Open Shift 中应用管理部署的一些笔记

写在前面


因为参加考试,会陆续分享一些 OpenShift 的笔记,博文内容为介绍 openshift 不同的创建应用的方式,包括:

  • 基于 IS 创建应用
  • 基于镜像创建应用
  • 基于源码和 image 创建应用
  • 基于源码和 IS 创建应用
  • 基于模板创建应用

学习环境为 openshift v3 的版本,有些旧,这里如果专门学习 openshift ,建议学习 v4 版本。

应用创建


为了在 OpenShift 中创建新应用程序,您可以使用 oc new-app 命令创建应用,使用 –strategy 标志来指定要使用的构建策略。–strategy 标志可以采用多个值,包括:

  • docker:此策略从 Dockerfile 构建应用程序。
  • source:此策略使用 Source-to-Image (S2I) 工具从源代码构建应用程序。
  • pipeline:此策略使用 Jenkins 管道构建应用程序。

使用了 –strategy=source 标志,这意味着 OpenShift 将使用 S2I 工具从源代码构建应用程序。S2I 是 OpenShift 中的一个工具,它允许开发人员从他们的源代码构建可重现的 Docker 镜像。S2I 通过提供构建和运行容器应用程序的框架简化了构建镜像的过程。

S2I 的工作原理是将您的源代码与基础镜像结合起来创建一个新的镜像,该镜像可以在容器中运行。基础镜像为您的应用程序提供运行时环境,而源代码则提供应用程序代码。S2I 还允许您通过提供可以在构建过程中运行的脚本来自定义构建过程。

要在 OpenShift 中创建 S2I 构建,您可以使用 oc new-app 命令和 –strategy=source 标志。这将创建一个新的构建配置,该配置使用 S2I 构建您的应用程序。然后,您可以将源代码推送到构建配置中,OpenShift 将自动为您构建一个新的镜像。

以下是使用 oc new-app 命令在 OpenShift 中创建 S2I 构建的示例:

基于 IS 创建应用


$   oc  new-app  --name=mysql   -i  mysql:latest  -e  MYSQL_ROOT_PASSWORD=redhat   

使用 -i, --image-stream 指定 IS 的镜像位置

要在 OpenShift 上创建一个基于 ImageStream (IS) 的应用,可以按照以下步骤进行操作:

  • 1.创建一个新项目或选择一个现有项目。
  • 2.运行以下命令创建一个 ImageStream:
  # 这将在当前项目中创建一个指定名称的新 ImageStream。
   oc create is <imagestream-name>
  • 3.运行以下命令将镜像导入 ImageStream:
   #这将从指定的 URL 导入镜像到 ImageStream 中。
   oc import-image <imagestream-name> --from=<image-url> --confirm
  • 4.运行以下命令创建一个新应用:
   oc new-app -i <imagestream-name>

这将创建一个基于 ImageStream 的新应用程序。

在此过程中,将自动生成多个 API 资源对象,包括:

ImageStream
ImageStreamTag
DeploymentConfig
Deployment
Replicationcontroller
Replicaset
Service
Route(路由对象需要手动创建)

当镜像被导入 ImageStream 时,将创建 ImageStream 和 ImageStreamTag 资源。当创建新应用程序时,将创建 DeploymentConfig、Service 和 Route 资源。

这里我们看一个 Demo,创建一个 ImageStream:

┌──[root@vms16.liruilongs.github.io]-[~]
└─$   oc create is myimagestream
imagestream.image.openshift.io/myimagestream created

将镜像导入 ImageStream:

┌──[root@vms16.liruilongs.github.io]-[~]
└─$   oc import-image myimagestream --from=docker.io/nginx --confirm
imagestream.image.openshift.io/myimagestream imported

Name:                   myimagestream
Namespace:              myproject
Created:                14 seconds ago
Labels:                 <none>
Annotations:            openshift.io/image.dockerRepositoryCheck=2023-04-16T03:21:19Z
Docker Pull Spec:       172.30.1.1:5000/myproject/myimagestream
Image Lookup:           local=false
Unique Images:          1
Tags:                   1

latest
  tagged from docker.io/nginx

  * docker.io/nginx@sha256:f2fee5c7194cbbfb9d2711fa5de094c797a42a51aa42b0c8ee8ca31547c872b1
      Less than a second ago

Image Name:     myimagestream:latest
Docker Image:   docker.io/nginx@sha256:f2fee5c7194cbbfb9d2711fa5de094c797a42a51aa42b0c8ee8ca31547c872b1
Name:           sha256:f2fee5c7194cbbfb9d2711fa5de094c797a42a51aa42b0c8ee8ca31547c872b1
Created:        Less than a second ago
Annotations:    image.openshift.io/dockerLayersOrder=ascending
Image Size:     57.01MB in 6 layers
Layers:         31.42MB sha256:26c5c85e47da3022f1bdb9a112103646c5c29517d757e95426f16e4bd9533405
                25.58MB sha256:4f3256bdf66bf00bcec08043e67a80981428f0e0de12f963eac3c753b14d101d
                626B    sha256:2019c71d56550b97ce01e0b6ef8e971fec705186f2927d2cb109ac3e18edb0ac
                958B    sha256:8c767bdbc9aedd4bbf276c6f28aad18251cceacb768967c5702974ae1eac23cd
                773B    sha256:78e14bb05fd35b58587cd0c5ca2c2eb12b15031633ec30daa21c0ea3d2bb2a15
                1.406kB sha256:75576236abf5959ff23b741ed8c4786e244155b9265db5e6ecda9d8261de529f
Image Created:  3 days ago
Author:         <none>
Arch:           amd64
Entrypoint:     /docker-entrypoint.sh
Command:        nginx -g daemon off;
Working Dir:    <none>
User:           <none>
Exposes Ports:  80/tcp
Docker Labels:  maintainer=NGINX Docker Maintainers <docker-maint@nginx.com>
Environment:    PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
                NGINX_VERSION=1.23.4
                NJS_VERSION=0.7.11
                PKG_RELEASE=1~bullseye

基于 ImageStream 创建一个新应用程序:

┌──[root@vms16.liruilongs.github.io]-[~]
└─$   oc new-app myimagestream
--> Found image 6efc10a (3 days old) in image stream "myproject/myimagestream" under tag "latest" for "myimagestream"

    * This image will be deployed in deployment config "myimagestream"
    * Port 80/tcp will be load balanced by service "myimagestream"
      * Other containers can access this service through the hostname "myimagestream"
    * WARNING: Image "myproject/myimagestream:latest" runs as the 'root' user which may not be permitted by your cluster administrator

--> Creating resources ...
    deploymentconfig.apps.openshift.io "myimagestream" created
    service "myimagestream" 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 svc/myimagestream'
    Run 'oc status' to view your app.

默认生成的资源,可以看到通过 IS 创建应用会生成

┌──[root@vms16.liruilongs.github.io]-[~]
└─$oc get all
NAME                         READY     STATUS              RESTARTS   AGE
pod/myimagestream-1-9gfgs    0/1       ContainerCreating   0          23s
pod/myimagestream-1-deploy   1/1       Running             0          24s

NAME                                    DESIRED   CURRENT   READY     AGE
replicationcontroller/myimagestream-1   1         1         0         24s

NAME                    TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)   AGE
service/myimagestream   ClusterIP   172.30.226.178   <none>        80/TCP    24s

NAME                      DESIRED   CURRENT   UP-TO-DATE   AVAILABLE   AGE
deployment.apps/testpod   0         0         0            0           322d

NAME                                 DESIRED   CURRENT   READY     AGE
replicaset.apps/testpod-6fd8cb8d9f   0         0         0         322d

NAME                                               REVISION   DESIRED   CURRENT   TRIGGERED BY
deploymentconfig.apps.openshift.io/myimagestream   1          1         1         config,image(myimagestream:latest)

NAME                                           DOCKER REPO                               TAGS      UPDATED
imagestream.image.openshift.io/myimagestream   172.30.1.1:5000/myproject/myimagestream   latest    46 seconds ago
┌──[root@vms16.liruilongs.github.io]-[~]
└─$

基于镜像创建应用


$ oc    new-app --docker-image=registry.lab.example.com/openshift/hello-openshift --name=hello   

在 OpenShift 上基于 Docker 镜像创建应用,可以使用oc new-app命令。该命令将基于提供的 Docker 镜像创建新的应用程序和构建配置。

在创建过程中,OpenShift 将自动生成多个 API 资源对象,包括

  • DeploymentConfig
  • ImageStream
  • Replicationcontroller
  • router(路由需要自己创建)

这些对象用于管理应用程序及其相关资源。

看一个Demo

[root@master ~]# oc project samples
Now using project "samples" on server "https://master.lab.example.com:443".

在创建的项目下通过镜像构建应用

[root@master ~]# oc new-app --docker-image=registry.lab.example.com/openshift/hello-openshift --name=greeter
--> Found Docker image 7af3297 (4 years old) from registry.lab.example.com for "registry.lab.example.com/openshift/hello-openshift"

    * An image stream will be created as "greeter:latest" that will track this image
    * This image will be deployed in deployment config "greeter"
    * Ports 8080/tcp, 8888/tcp will be load balanced by service "greeter"
      * Other containers can access this service through the hostname "greeter"

--> Creating resources ...
    imagestream "greeter" created
    deploymentconfig "greeter" created
    service "greeter" 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 svc/greeter'
    Run 'oc status' to view your app.

查看创建过程

[root@master ~]# oc status
In project samples on server https://master.lab.example.com:443

svc/greeter - 172.30.106.99 ports 8080, 8888
  dc/greeter deploys istag/greeter:latest
    deployment #1 deployed 9 seconds ago - 1 pod


2 infos identified, use 'oc status -v' to see details.
[root@master ~]# oc status -v
In project samples on server https://master.lab.example.com:443

svc/greeter - 172.30.106.99 ports 8080, 8888
  dc/greeter deploys istag/greeter:latest
    deployment #1 deployed about a minute ago - 1 pod

Info:
  * dc/greeter has no readiness probe to verify pods are ready to accept traffic or ensure deployment is successful.
    try: oc set probe dc/greeter --readiness ...
  * dc/greeter has no liveness probe to verify pods are still running.
    try: oc set probe dc/greeter --liveness ...

View details with 'oc describe <resource>/<name>' or list everything with 'oc get all'.

查看通镜像直接构建生成的 API 资源对象

[root@master ~]# oc get all
NAME                        REVISION   DESIRED   CURRENT   TRIGGERED BY
deploymentconfigs/greeter   1          1         1         config,image(greeter:latest)

NAME                   DOCKER REPO                                        TAGS      UPDATED
imagestreams/greeter   docker-registry.default.svc:5000/samples/greeter   latest    About a minute ago

NAME                 READY     STATUS    RESTARTS   AGE
po/greeter-1-gm5qg   1/1       Running   0          1m

NAME           DESIRED   CURRENT   READY     AGE
rc/greeter-1   1         1         1         1m

NAME          TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)             AGE
svc/greeter   ClusterIP   172.30.106.99   <none>        8080/TCP,8888/TCP   1m
[root@master ~]#

有些路由可能需要 TSL 等

[root@master ~]# ./gencert.sh greeter.apps.lab.example.com
Generating a private key...
Generating RSA private key, 2048 bit long modulus
............................................................................................+++
....................+++
e is 65537 (0x10001)

Generating a CSR...

Generating a certificate...
Signature ok
subject=/C=US/ST=NC/L=Raleigh/O=RedHat/OU=RHT/CN=greeter.apps.lab.example.com
Getting Private key

DONE.

创建一个支持 https 的路由

[root@master ~]# oc get svc
NAME      TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)             AGE
greeter   ClusterIP   172.30.106.99   <none>        8080/TCP,8888/TCP   6m
[root@master ~]# oc create route edge --service=greeter  --hostname=greeter.apps.lab.example.com --key=greeter.apps.lab.example.com.key --cert=greeter.apps.lab.example.com.crt
route "greeter" created
[root@master ~]# oc get route
NAME      HOST/PORT                      PATH      SERVICES   PORT       TERMINATION   WILDCARD
greeter   greeter.apps.lab.example.com             greeter    8080-tcp   edge          None
[root@master ~]# curl greeter.apps.lab.example.com

生成证书文件

[root@master ~]# cat gencert.sh
#!/bin/bash

echo "Generating a private key..."
openssl genrsa -out $1.key 2048
echo

echo "Generating a CSR..."
openssl req -new -key $1.key -out $1.csr -subj "/C=US/ST=NC/L=Raleigh/O=RedHat/OU=RHT/CN=$1"
echo

echo "Generating a certificate..."
openssl x509 -req -days 366 -in $1.csr -signkey $1.key -out $1.crt
echo
echo  "DONE."
echo
[root@master ~]#

基于源码和 image 创建应用


[root@master ~]# oc new-app registry.lab.example.com/rhscl/php-70-rhel7~http://services.lab.example.com
/php-helloworld
--> Found Docker image c101534 (5 years old) from registry.lab.example.com for "registry.lab.example.com/rhscl/php-70-rhel7"

    Apache 2.4 with PHP 7.0
    -----------------------
    PHP 7.0 available as docker container is a base platform for building and running various PHP 7.0 applications and frameworks. PHP is an HTML-embedded scripting language. PHP attempts to make it easy for developers to write dynamically generated web pages. PHP also offers built-in database integration for several commercial and non-commercial database management systems, so writing a database-enabled webpage with PHP is fairly simple. The most common use of PHP coding is probably as a replacement for CGI scripts.

    Tags: builder, php, php70, rh-php70

    * An image stream will be created as "php-70-rhel7:latest" that will track the source image
    * A source build using source code from http://services.lab.example.com/php-helloworld will be created
      * The resulting image will be pushed to image stream "php-helloworld:latest"
      * Every time "php-70-rhel7:latest" changes a new build will be triggered
    * This image will be deployed in deployment config "php-helloworld"
    * Port 8080/tcp will be load balanced by service "php-helloworld"
      * Other containers can access this service through the hostname "php-helloworld"

--> Creating resources ...
    imagestream "php-70-rhel7" created
    imagestream "php-helloworld" created
    buildconfig "php-helloworld" created
    deploymentconfig "php-helloworld" created
    service "php-helloworld" created
--> Success
    Build scheduled, use 'oc logs -f bc/php-helloworld' 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 svc/php-helloworld'
    Run 'oc status' to view your app.
[root@master ~]# oc logs -f bc/php-helloworld
Cloning "http://services.lab.example.com/php-helloworld" ...
        Commit: 6d61e75647124d02aa761f994532ef29eae46f8e (Establish remote repository)
        Author: root <root@services.lab.example.com>
        Date:   Thu Aug 9 11:33:29 2018 -0700
---> Installing application source...

Pushing image docker-registry.default.svc:5000/rome/php-helloworld:latest ...
Pushed 0/6 layers, 1% complete
Pushed 1/6 layers, 25% complete
Pushed 2/6 layers, 42% complete
Pushed 3/6 layers, 59% complete
Pushed 4/6 layers, 81% complete
Pushed 5/6 layers, 100% complete
Pushed 6/6 layers, 100% complete
Push successful
[root@master ~]#
[root@master ~]# oc get all
NAME                               REVISION   DESIRED   CURRENT   TRIGGERED BY
deploymentconfigs/php-helloworld   1          1         1         config,image(php-helloworld:latest)

NAME                          TYPE      FROM      LATEST
buildconfigs/php-helloworld   Source    Git       1

NAME                      TYPE      FROM          STATUS     STARTED         DURATION
builds/php-helloworld-1   Source    Git@6d61e75   Complete   2 minutes ago   1m12s

NAME                          DOCKER REPO                                            TAGS      UPDATED
imagestreams/php-70-rhel7     docker-registry.default.svc:5000/rome/php-70-rhel7     latest    2 minutes ago
imagestreams/php-helloworld   docker-registry.default.svc:5000/rome/php-helloworld   latest    About a minute ago

NAME                        READY     STATUS      RESTARTS   AGE
po/php-helloworld-1-8hvvn   1/1       Running     0          1m
po/php-helloworld-1-build   0/1       Completed   0          2m

NAME                  DESIRED   CURRENT   READY     AGE
rc/php-helloworld-1   1         1         1         1m

NAME                 TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)    AGE
svc/php-helloworld   ClusterIP   172.30.69.166   <none>        8080/TCP   2m
[root@master ~]#
[root@master ~]# oc expose svc/php-helloworld  --hostname=hellophp.apps.lab.example.com
route "php-helloworld" exposed
[root@master ~]# oc get route
NAME             HOST/PORT                       PATH      SERVICES         PORT       TERMINATION   WILDCARD
php-helloworld   hellophp.apps.lab.example.com             php-helloworld   8080-tcp                 None
[root@master ~]# curl hellophp.apps.lab.example.com
Hello, World! php version is 7.0.10
[root@master ~]#

持续构建

[root@master php-helloworld]# oc start-build php-helloworld
build "php-helloworld-2" started
[root@master php-helloworld]# oc get dc
NAME             REVISION   DESIRED   CURRENT   TRIGGERED BY
php-helloworld   2          1         0         config,image(php-helloworld:latest)
[root@master php-helloworld]# oc get build
NAME               TYPE      FROM          STATUS     STARTED          DURATION
php-helloworld-1   Source    Git@6d61e75   Complete   10 minutes ago   1m12s
php-helloworld-2   Source    Git@2210bc1   Complete   15 seconds ago   8s

基于源码和 IS 创建应用


$oc new-app  --name=hello    -i    php:7.0    http://registry.lab.example.com/scaling   

这里实际上和上面的一样,不再说明

基于模板创建应用


$    oc    new-app    --template=ruby-helloworld-sample    --param=MYSQL_USER=admin $    oc    new-app    --file=./example/myapp/template.json    --param=MYSQL_USER=admi n  

以下是使用模板在OpenShift中创建应用的步骤:

  • 使用 oc login 命令登录到您的OpenShift集群。
  • 使用 oc new-project 命令创建一个新项目。
  • 使用 oc get templates -n openshift 命令浏览可用的模板。
  • 选择适合您需求的模板,使用 oc new-app 命令创建一个应用。您可以使用 -p 标志指定模板名称和任何参数值。
  • 使用 oc get pods 命令监视部署。

当您从模板创建应用时,OpenShift会创建多个资源对象,包括DeploymentConfig、Service、Route和ImageStream。这些对象一起工作,以部署和公开您的应用程序。

DeploymentConfig对象定义了应用程序的部署方式,包括副本数、要使用的容器映像以及任何环境变量或卷挂载。Service对象为您的应用程序提供稳定的IP地址和DNS名称,允许其他服务与其通信。Route对象将您的应用程序公开给外部世界,提供用户可以访问的URL。最后,ImageStream对象跟踪应用程序使用的容器映像,允许您回滚到以前的版本(如果需要)。

一个 模板 yaml 文件 Demo

[root@master ~]# cat gogs-temp.yaml
kind: Template
apiVersion: v1
metadata:
  annotations:
    description: The Gogs git server (https://gogs.io/)
    tags: instant-app,gogs,go,golang
  name: gogs
objects:
- kind: PersistentVolume
  apiVersion: v1
  metadata:
    name: gogs-postgres-data
  spec:
    capacity:
      storage: 2Gi
    accessModes:
    - ReadWriteMany
    nfs:
      path: /exports/gogs-postgres-data
      server: services.lab.example.com
    persistentVolumeReclaimPolicy: Recycle

- kind: PersistentVolume
  apiVersion: v1
  metadata:
    name: gogs-data
  spec:
    capacity:
      storage: 1Gi
    accessModes:
    - ReadWriteMany
    nfs:
      path: /exports/gogs-data
      server: services.lab.example.com
    persistentVolumeReclaimPolicy: Recycle

- kind: ServiceAccount
  apiVersion: v1
  metadata:
    creationTimestamp: null
    labels:
      app: ${APPLICATION_NAME}
    name: ${APPLICATION_NAME}
- kind: Service
  apiVersion: v1
  metadata:
    annotations:
      description: Exposes the database server
    name: ${APPLICATION_NAME}-postgresql
    labels:
      app: ${APPLICATION_NAME}
  spec:
    ports:
    - name: postgresql
      port: 5432
      targetPort: 5432
    selector:
      name: ${APPLICATION_NAME}-postgresql
- kind: DeploymentConfig
  apiVersion: v1
  metadata:
    annotations:
      description: Defines how to deploy the database
    name: ${APPLICATION_NAME}-postgresql
    labels:
      app: ${APPLICATION_NAME}
  spec:
    replicas: 1
    selector:
      name: ${APPLICATION_NAME}-postgresql
    strategy:
      type: Recreate
    template:
      metadata:
        labels:
          name: ${APPLICATION_NAME}-postgresql
        name: ${APPLICATION_NAME}-postgresql
      spec:
        serviceAccountName: ${APPLICATION_NAME}
        containers:
        - env:
          - name: POSTGRESQL_USER
            value: ${DATABASE_USER}
          - name: POSTGRESQL_PASSWORD
            value: ${DATABASE_PASSWORD}
          - name: POSTGRESQL_DATABASE
            value: ${DATABASE_NAME}
          - name: POSTGRESQL_MAX_CONNECTIONS
            value: ${DATABASE_MAX_CONNECTIONS}
          - name: POSTGRESQL_SHARED_BUFFERS
            value: ${DATABASE_SHARED_BUFFERS}
          - name: POSTGRESQL_ADMIN_PASSWORD
            value: ${DATABASE_ADMIN_PASSWORD}
          image: ' '
          livenessProbe:
            initialDelaySeconds: 30
            tcpSocket:
              port: 5432
            timeoutSeconds: 1
            failureThreshold: 10
            periodSeconds: 20
          name: postgresql
          ports:
          - containerPort: 5432
          readinessProbe:
            exec:
              command:
              - /bin/sh
              - -i
              - -c
              - psql -h 127.0.0.1 -U ${POSTGRESQL_USER} -q -d ${POSTGRESQL_DATABASE} -c 'SELECT 1'
            initialDelaySeconds: 5
            timeoutSeconds: 1
            failureThreshold: 10
          resources:
            limits:
              memory: 512Mi
          volumeMounts:
          - mountPath: /var/lib/pgsql/data
            name: gogs-postgres-data
        volumes:
        - name: gogs-postgres-data
          persistentVolumeClaim:
            claimName: gogs-postgres-data
    triggers:
    - imageChangeParams:
        automatic: true
        containerNames:
        - postgresql
        from:
          kind: ImageStreamTag
          name: postgresql:9.5
          namespace: openshift
      type: ImageChange
    - type: ConfigChange
- kind: Service
  apiVersion: v1
  metadata:
    annotations:
      description: The Gogs server's http port
      service.alpha.openshift.io/dependencies: '[{"name":"${APPLICATION_NAME}-postgresql","namespace":"","kind":"Service"}]'
    labels:
      app: ${APPLICATION_NAME}
    name: ${APPLICATION_NAME}
  spec:
    ports:
    - name: 3000-tcp
      port: 3000
      protocol: TCP
      targetPort: 3000
    selector:
      app: ${APPLICATION_NAME}
      deploymentconfig: ${APPLICATION_NAME}
    sessionAffinity: None
    type: ClusterIP
  status:
    loadBalancer: {}
- kind: Route
  apiVersion: v1
  id: ${APPLICATION_NAME}-http
  metadata:
    annotations:
      description: Route for application's http service.
    labels:
      app: ${APPLICATION_NAME}
    name: ${APPLICATION_NAME}
  spec:
    host: ${HOSTNAME}
    to:
      name: ${APPLICATION_NAME}
- kind: DeploymentConfig
  apiVersion: v1
  metadata:
    labels:
      app: ${APPLICATION_NAME}
    name: ${APPLICATION_NAME}
  spec:
    replicas: 1
    selector:
      app: ${APPLICATION_NAME}
      deploymentconfig: ${APPLICATION_NAME}
    strategy:
      resources: {}
      rollingParams:
        intervalSeconds: 1
        maxSurge: 25%
        maxUnavailable: 25%
        timeoutSeconds: 600
        updatePeriodSeconds: 1
      type: Rolling
    template:
      metadata:
        creationTimestamp: null
        labels:
          app: ${APPLICATION_NAME}
          deploymentconfig: ${APPLICATION_NAME}
      spec:
        serviceAccountName: ${APPLICATION_NAME}
        containers:
        - image: " "
          imagePullPolicy: Always
          name: ${APPLICATION_NAME}
          ports:
          - containerPort: 3000
            protocol: TCP
          resources: {}
          terminationMessagePath: /dev/termination-log
          volumeMounts:
          - name: gogs-data
            mountPath: /opt/gogs/data
          - name: gogs-config
            mountPath: /etc/gogs/conf
          readinessProbe:
              httpGet:
                path: /
                port: 3000
                scheme: HTTP
              initialDelaySeconds: 3
              timeoutSeconds: 1
              periodSeconds: 20
              successThreshold: 1
              failureThreshold: 10
          livenessProbe:
              httpGet:
                path: /
                port: 3000
                scheme: HTTP
              initialDelaySeconds: 20
              timeoutSeconds: 1
              periodSeconds: 10
              successThreshold: 1
              failureThreshold: 10
        dnsPolicy: ClusterFirst
        restartPolicy: Always
        securityContext: {}
        terminationGracePeriodSeconds: 30
        volumes:
        - name: gogs-data
          persistentVolumeClaim:
            claimName: gogs-data
        - name: gogs-config
          configMap:
            name: gogs-config
            items:
              - key: app.ini
                path: app.ini
    test: false
    triggers:
    - type: ConfigChange
    - imageChangeParams:
        automatic: true
        containerNames:
        - ${APPLICATION_NAME}
        from:
          kind: ImageStreamTag
          name: ${APPLICATION_NAME}:${GOGS_VERSION}
      type: ImageChange
- kind: ImageStream
  apiVersion: v1
  metadata:
    labels:
      app: ${APPLICATION_NAME}
    name: ${APPLICATION_NAME}
  spec:
    tags:
    - name: "${GOGS_VERSION}"
      from:
        kind: DockerImage
        name: services.lab.example.com/openshiftdemos/gogs:0.9.97
      importPolicy: {
            "insecure":true
         }
      annotations:
        description: The Gogs git server docker image
        tags: gogs,go,golang
        version: "${GOGS_VERSION}"
- kind: PersistentVolumeClaim
  apiVersion: v1
  metadata:
    name: gogs-data
    labels:
      app: ${APPLICATION_NAME}
  spec:
    accessModes:
      - ReadWriteMany
    resources:
      requests:
        storage: ${GOGS_VOLUME_CAPACITY}
- kind: PersistentVolumeClaim
  apiVersion: v1
  metadata:
    name: gogs-postgres-data
    labels:
      app: ${APPLICATION_NAME}
  spec:
    accessModes:
      - ReadWriteMany
    resources:
      requests:
        storage: ${DB_VOLUME_CAPACITY}
- kind: ConfigMap
  apiVersion: v1
  metadata:
    name: gogs-config
    labels:
      app: ${APPLICATION_NAME}
  data:
    app.ini: |
      RUN_MODE = prod
      RUN_USER = gogs

      [database]
      DB_TYPE  = postgres
      HOST     = ${APPLICATION_NAME}-postgresql:5432
      NAME     = ${DATABASE_NAME}
      USER     = ${DATABASE_USER}
      PASSWD   = ${DATABASE_PASSWORD}

      [repository]
      ROOT = /opt/gogs/data/repositories

      [server]
      ROOT_URL=http://${HOSTNAME}
      SSH_DOMAIN=${HOSTNAME}

      [security]
      INSTALL_LOCK = ${INSTALL_LOCK}

      [service]
      ENABLE_CAPTCHA = false

      [webhook]
      SKIP_TLS_VERIFY = ${SKIP_TLS_VERIFY}
parameters:
- description: The name for the application.
  name: APPLICATION_NAME
  required: true
  value: gogs
- description: 'Custom hostname for http service route.  Leave blank for default hostname, e.g.: <application-name>-<project>.<default-domain-suffix>'
  name: HOSTNAME
  required: true
- description: Volume space available for data, e.g. 512Mi, 2Gi
  name: GOGS_VOLUME_CAPACITY
  required: true
  value: 1Gi
- description: Volume space available for postregs data, e.g. 512Mi, 2Gi
  name: DB_VOLUME_CAPACITY
  required: true
  value: 2Gi
- displayName: Database Username
  from: gogs
  value: gogs
  name: DATABASE_USER
- displayName: Database Password
  from: '[a-zA-Z0-9]{8}'
  value: gogs
  name: DATABASE_PASSWORD
- displayName: Database Name
  name: DATABASE_NAME
  value: gogs
- displayName: Database Admin Password
  from: '[a-zA-Z0-9]{8}'
  generate: expression
  name: DATABASE_ADMIN_PASSWORD
- displayName: Maximum Database Connections
  name: DATABASE_MAX_CONNECTIONS
  value: "100"
- displayName: Shared Buffer Amount
  name: DATABASE_SHARED_BUFFERS
  value: 12MB
- name: GOGS_VERSION
  displayName: Gogs Version
  description: 'Version of the Gogs container image to be used (check the available version https://hub.docker.com/r/openshiftdemos/gogs/tags)'
  value: "0.9.97"
  required: true
- name: INSTALL_LOCK
  displayName: Installation lock
  description: 'If set to true, installation (/install) page will be disabled. Set to false if you want to run the installation wizard via web'
  value: "true"
- name: SKIP_TLS_VERIFY
  displayName: Skip TLS verification on webhooks
  description: Skip TLS verification on webhooks. Enable with caution!
  value: "false"
[root@master ~]# gogs-temp.yaml

通过 yaml 文件创建 模板

[root@master ~]# oc apply -f gogs-temp.yaml -n openshift
template "gogs" created

通过模板运行应用

[root@master ~]# oc new-app --template=gogs  --param=HOSTNAME=gogs.apps.lab.example.com
--> Deploying template "openshift/gogs" to project ditto

     gogs
     ---------
     The Gogs git server (https://gogs.io/)

     * With parameters:
        * APPLICATION_NAME=gogs
        * HOSTNAME=gogs.apps.lab.example.com
        * GOGS_VOLUME_CAPACITY=1Gi
        * DB_VOLUME_CAPACITY=2Gi
        * Database Username=gogs
        * Database Password=gogs
        * Database Name=gogs
        * Database Admin Password=iaHaUYMy # generated
        * Maximum Database Connections=100
        * Shared Buffer Amount=12MB
        * Gogs Version=0.9.97
        * Installation lock=true
        * Skip TLS verification on webhooks=false

--> Creating resources ...
    persistentvolume "gogs-postgres-data" created
    persistentvolume "gogs-data" created
    serviceaccount "gogs" created
    service "gogs-postgresql" created
    deploymentconfig "gogs-postgresql" created
    service "gogs" created
    route "gogs" created
    deploymentconfig "gogs" created
    imagestream "gogs" created
    persistentvolumeclaim "gogs-data" created
    persistentvolumeclaim "gogs-postgres-data" created
    configmap "gogs-config" created
--> Success
    Access your application via route 'gogs.apps.lab.example.com'
    Run 'oc status' to view your app.
[root@master ~]#

查看所有资源

[root@master ~]# oc get all
NAME                                REVISION   DESIRED   CURRENT   TRIGGERED BY
deploymentconfigs/gogs              0          1         0         config,image(gogs:0.9.97)
deploymentconfigs/gogs-postgresql   1          1         1         config,image(postgresql:9.2)

NAME                DOCKER REPO                                   TAGS      UPDATED
imagestreams/gogs   docker-registry.default.svc:5000/ditto/gogs   0.9.97

NAME          HOST/PORT                   PATH      SERVICES   PORT      TERMINATION   WILDCARD
routes/gogs   gogs.apps.lab.example.com             gogs       <all>                   None

NAME                          READY     STATUS    RESTARTS   AGE
po/gogs-postgresql-1-9rjb2    0/1       Running   0          30s
po/gogs-postgresql-1-deploy   1/1       Running   0          33s

NAME                   DESIRED   CURRENT   READY     AGE
rc/gogs-postgresql-1   1         1         0         33s

NAME                  TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)    AGE
svc/gogs              ClusterIP   172.30.4.106     <none>        3000/TCP   33s
svc/gogs-postgresql   ClusterIP   172.30.127.172   <none>        5432/TCP   34s
[root@master ~]#