Menu Close
4.5.2. 创建 PostgreSQL 数据库实例
要创建 PostgreSQL 数据库
实例,您必须创建一个数据库自定义资源(CR)并配置数据库。
流程
通过在 shell 中运行以下命令来创建
Database
CR 和my-postgresql
命名空间:$ oc apply -f - << EOD apiVersion: postgresql.dev4devs.com/v1alpha1 kind: Database metadata: name: sampledatabase namespace: my-postgresql annotations: host: sampledatabase type: postgresql port: "5432" service.binding/database: 'path={.spec.databaseName}' service.binding/port: 'path={.metadata.annotations.port}' service.binding/password: 'path={.spec.databasePassword}' service.binding/username: 'path={.spec.databaseUser}' service.binding/type: 'path={.metadata.annotations.type}' service.binding/host: 'path={.metadata.annotations.host}' spec: databaseCpu: 30m databaseCpuLimit: 60m databaseMemoryLimit: 512Mi databaseMemoryRequest: 128Mi databaseName: "sampledb" databaseNameKeyEnvVar: POSTGRESQL_DATABASE databasePassword: "samplepwd" databasePasswordKeyEnvVar: POSTGRESQL_PASSWORD databaseStorageRequest: 1Gi databaseUser: "sampleuser" databaseUserKeyEnvVar: POSTGRESQL_USER image: registry.redhat.io/rhel8/postgresql-96:latest databaseStorageClassName: nfs-storage-provisioner size: 1 EOD
此
Database
CR 中添加的注解启用服务绑定连接并触发 Operator 协调。输出会验证数据库实例是否已创建:
输出示例
database.postgresql.dev4devs.com/sampledatabase created
创建数据库实例后,请确保
my-postgresql
命名空间中的所有 pod 都在运行(需要几分钟):$ oc get pods -n my-postgresql
输出会验证数据库是否已创建:
输出示例
NAME READY STATUS RESTARTS AGE sampledatabase-cbc655488-74kss 0/1 Running 0 32s
新数据库在此阶段为空。您可以设置其架构,并规划一个示例数据集以与示例应用程序交互。
使用 schema 和示例数据初始化数据库。要做到这一点,请通过将代码复制到 shell 并运行它来使用以下自定义 shell 脚本:
$ cat << EOD | bash #!/bin/bash export pgo_cluster_name=sampledb export cluster_namespace=my-postgresql export pgo_cluster_username=sampleuser nohup oc -n "\${cluster_namespace}" port-forward svc/sampledatabase 5432:5432 & sleep 5 curl -LO https://raw.githubusercontent.com/spring-petclinic/spring-petclinic-rest/master/src/main/resources/db/postgresql/initDB.sql psql -h localhost -U "\${pgo_cluster_username}" "\${pgo_cluster_name}" -f initDB.sql curl -LO https://raw.githubusercontent.com/spring-petclinic/spring-petclinic-rest/master/src/main/resources/db/postgresql/populateDB.sql psql -h localhost -U "\${pgo_cluster_username}" "\${pgo_cluster_name}" -f populateDB.sql EOD
终端中的输出显示您正在为应用配置了数据库。
配置了数据库后,您可以部署示例应用程序并将其连接到数据库服务。