{"id":15729250,"url":"https://github.com/jxlwqq/guestbook-operator","last_synced_at":"2026-04-29T18:32:28.651Z","repository":{"id":149126121,"uuid":"405886326","full_name":"jxlwqq/guestbook-operator","owner":"jxlwqq","description":"「Kubernetes 官方示例：使用 Redis 部署 PHP 留言板应用程序」Operator 化。","archived":false,"fork":false,"pushed_at":"2021-09-18T08:36:32.000Z","size":88,"stargazers_count":1,"open_issues_count":1,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-03-31T02:32:45.927Z","etag":null,"topics":["guestbook","kubernetes","olm","operator-framework","operator-sdk"],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/jxlwqq.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-09-13T08:07:19.000Z","updated_at":"2021-09-18T08:36:34.000Z","dependencies_parsed_at":null,"dependency_job_id":"e94ce4b5-70ee-4066-ac9c-a76db13cfd80","html_url":"https://github.com/jxlwqq/guestbook-operator","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/jxlwqq/guestbook-operator","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jxlwqq%2Fguestbook-operator","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jxlwqq%2Fguestbook-operator/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jxlwqq%2Fguestbook-operator/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jxlwqq%2Fguestbook-operator/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/jxlwqq","download_url":"https://codeload.github.com/jxlwqq/guestbook-operator/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jxlwqq%2Fguestbook-operator/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":32439179,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-29T18:12:22.909Z","status":"ssl_error","status_checked_at":"2026-04-29T18:11:33.322Z","response_time":110,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["guestbook","kubernetes","olm","operator-framework","operator-sdk"],"created_at":"2024-10-03T23:20:52.160Z","updated_at":"2026-04-29T18:32:28.636Z","avatar_url":"https://github.com/jxlwqq.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"# guestbook-operator\n\n「[Kubernetes 官方示例：使用 Redis 部署 PHP 留言板应用程序](https://kubernetes.io/docs/tutorials/stateless-application/guestbook/)」Operator 化。\n\n### 前置条件\n\n* 安装 Docker Desktop，并启动内置的 Kubernetes 集群\n* 注册一个 [hub.docker.com](https://hub.docker.com/) 账户，需要将本地构建好的镜像推送至公开仓库中\n* 安装 operator SDK CLI: `brew install operator-sdk`\n* 安装 Go: `brew install go`\n\n本示例推荐的依赖版本：\n\n* Docker Desktop: \u003e= 4.0.0\n* Kubernetes: \u003e= 1.21.4\n* Operator-SDK: \u003e= 1.11.0\n* Go: \u003e= 1.17\n\n\u003e jxlwqq 为笔者的 ID，命令行和代码中涉及的个人 ID，均需要替换为读者自己的，包括\n\u003e * 命令行参数中的 `--domain=`\n\u003e * 命令行参数中的 `--repo=`\n\u003e * controllers/guestbook_controller.go 文件中的 `//+kubebuilder:rbac:groups=`\n\u003e * Makefile 文件中的 `IMAGE_TAG_BASE ?=`\n\n### 创建项目\n\n使用 Operator SDK CLI 创建名为 guestbook-operator 的项目。\n\n```shell\nmkdir -p $HOME/projects/guestbook-operator\ncd $HOME/projects/guestbook-operator\ngo env -w GOPROXY=https://goproxy.cn,direct\n```shell\n\noperator-sdk init \\\n--domain=jxlwqq.github.io \\\n--repo=github.com/jxlwqq/guestbook-operator \\\n--skip-go-version-check\n```\n\n\n### 创建 API 和控制器\n\n使用 Operator SDK CLI 创建自定义资源定义（CRD）API 和控制器。\n\n运行以下命令创建带有组 app、版本 v1alpha1 和种类 Guestbook 的 API：\n\n```shell\noperator-sdk create api \\\n--resource=true \\\n--controller=true \\\n--group=app \\\n--version=v1alpha1 \\\n--kind=Guestbook\n```\n\n\n定义 Guestbook 自定义资源（CR）的 API。\n\n修改 api/v1alpha1/guestbook_types.go 中的 Go 类型定义，使其具有以下 spec 和 status\n\n```go\ntype GuestbookSpec struct {\n\tFrontendSize int32 `json:\"frontendSize\"`\n\tRedisFollowerSize int32 `json:\"redisFollowerSize\"`\n}\n```\n\n\n\n为资源类型更新生成的代码：\n```shell\nmake generate\n```\n\n\n运行以下命令以生成和更新 CRD 清单：\n```shell\nmake manifests\n```\n\n\n### 实现控制器\n\n\u003e 由于逻辑较为复杂，代码较为庞大，所以无法在此全部展示，完整的操作器代码请参见 controllers 目录。\n在本例中，将生成的控制器文件 controllers/guestbook_controller.go 替换为以下示例实现：\n```go\n/*\nCopyright 2021.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\npackage controllers\n\nimport (\n\t\"context\"\n\tappsv1 \"k8s.io/api/apps/v1\"\n\tcorev1 \"k8s.io/api/core/v1\"\n\t\"k8s.io/apimachinery/pkg/api/errors\"\n\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\tctrl \"sigs.k8s.io/controller-runtime\"\n\t\"sigs.k8s.io/controller-runtime/pkg/client\"\n\t\"sigs.k8s.io/controller-runtime/pkg/log\"\n\n\tappv1alpha1 \"github.com/jxlwqq/guestbook-operator/api/v1alpha1\"\n)\n\n// GuestbookReconciler reconciles a Guestbook object\ntype GuestbookReconciler struct {\n\tclient.Client\n\tScheme *runtime.Scheme\n}\n\n//+kubebuilder:rbac:groups=app.jxlwqq.github.io,resources=guestbooks,verbs=get;list;watch;create;update;patch;delete\n//+kubebuilder:rbac:groups=app.jxlwqq.github.io,resources=guestbooks/status,verbs=get;update;patch\n//+kubebuilder:rbac:groups=app.jxlwqq.github.io,resources=guestbooks/finalizers,verbs=update\n//+kubebuilder:rbac:groups=apps,resources=deployments,verbs=get;list;watch;create;update;patch;delete\n//+kubebuilder:rbac:groups=core,resources=service,verbs=get;list;watch;create;update;patch;delete\n//+kubebuilder:rbac:groups=core,resources=pods,verbs=get;list;watch\n\n// Reconcile is part of the main kubernetes reconciliation loop which aims to\n// move the current state of the cluster closer to the desired state.\n// TODO(user): Modify the Reconcile function to compare the state specified by\n// the Guestbook object against the actual cluster state, and then\n// perform operations to make the cluster state reflect the state specified by\n// the user.\n//\n// For more details, check Reconcile and its Result here:\n// - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.9.2/pkg/reconcile\nfunc (r *GuestbookReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {\n\treqLogger := log.FromContext(ctx)\n\treqLogger.Info(\"Reconciling Guestbook\")\n\n\tguestbook := \u0026appv1alpha1.Guestbook{}\n\terr := r.Client.Get(context.TODO(), req.NamespacedName, guestbook)\n\tif err != nil {\n\t\tif errors.IsNotFound(err) {\n\t\t\treturn ctrl.Result{}, nil\n\t\t}\n\t\treturn ctrl.Result{}, err\n\t}\n\n\tvar result = \u0026ctrl.Result{}\n\n\tresult, err = r.ensureDeployment(r.redisLeaderDeployment(guestbook))\n\tif result != nil {\n\t\treturn *result, err\n\t}\n\tresult, err = r.ensureService(r.redisLeaderService(guestbook))\n\tif result != nil {\n\t\treturn *result, err\n\t}\n\n\tresult, err = r.ensureDeployment(r.redisFollowerDeployment(guestbook))\n\tif result != nil {\n\t\treturn *result, err\n\t}\n\tresult, err = r.ensureService(r.redisFollowerService(guestbook))\n\tif result != nil {\n\t\treturn *result, err\n\t}\n\tresult, err = r.handleRedisFollowerChanges(guestbook)\n\tif result != nil {\n\t\treturn *result, err\n\t}\n\n\tresult, err = r.ensureDeployment(r.frontendDeployment(guestbook))\n\tif result != nil {\n\t\treturn *result, err\n\t}\n\tresult, err = r.ensureService(r.frontendService(guestbook))\n\tif result != nil {\n\t\treturn *result, err\n\t}\n\tresult, err = r.handleFrontendChanges(guestbook)\n\tif result != nil {\n\t\treturn *result, err\n\t}\n\n\treturn ctrl.Result{}, nil\n}\n\n// SetupWithManager sets up the controller with the Manager.\nfunc (r *GuestbookReconciler) SetupWithManager(mgr ctrl.Manager) error {\n\treturn ctrl.NewControllerManagedBy(mgr).\n\t\tFor(\u0026appv1alpha1.Guestbook{}).\n\t\tOwns(\u0026appsv1.Deployment{}).\n\t\tOwns(\u0026corev1.Service{}).\n\t\tComplete(r)\n}\n```\n\n运行以下命令以生成和更新 CRD 清单：\n```shell\nmake manifests\n```\n\n### 运行 Operator\n\n捆绑 Operator，并使用 Operator Lifecycle Manager（OLM）在集群中部署。\n\n修改 Makefile 中 IMAGE_TAG_BASE 和 IMG：\n\n```makefile\nIMAGE_TAG_BASE ?= docker.io/jxlwqq/guestbook-operator\nIMG ?= $(IMAGE_TAG_BASE):latest\n```\n\n构建镜像：\n\n```shell\nmake docker-build\n```\n\n将镜像推送到镜像仓库：\n```shell\nmake docker-push\n```\n\n成功后访问：https://hub.docker.com/r/jxlwqq/guestbook-operator\n\n运行 make bundle 命令创建 Operator 捆绑包清单，并依次填入名称、作者等必要信息:\n```shell\nmake bundle\n```\n\n构建捆绑包镜像：\n```shell\nmake bundle-build\n```\n\n推送捆绑包镜像：\n```shell\nmake bundle-push\n```\n\n成功后访问：https://hub.docker.com/r/jxlwqq/guestbook-operator-bundle\n\n\n使用 Operator Lifecycle Manager 部署 Operator:\n\n```shell\n# 切换至本地集群\nkubectl config use-context docker-desktop\n# 安装 olm\noperator-sdk olm install\n# 使用 Operator SDK 中的 OLM 集成在集群中运行 Operator\noperator-sdk run bundle docker.io/jxlwqq/guestbook-operator-bundle:v0.0.1\n```\n\n### 创建自定义资源\n\n编辑 config/samples/app_v1alpha1_guestbook.yaml 上的 Guestbook CR 清单示例，使其包含以下规格：\n\n```yaml\napiVersion: app.jxlwqq.github.io/v1alpha1\nkind: Guestbook\nmetadata:\n  name: guestbook-sample\nspec:\n  # Add fields here\n  frontendSize: 2\n  redisFollowerSize: 2\n```\n\n创建 CR：\n```shell\nkubectl apply -f config/samples/app_v1alpha1_guestbook.yaml\n```\n\n查看 Pod：\n```shell\nNAME                              READY   STATUS    RESTARTS   AGE\nfrontend-85595f5bf9-jrcp4         1/1     Running   0          9s\nfrontend-85595f5bf9-q8fkl         1/1     Running   0          9s\nredis-follower-76c5cc5b79-fxxlq   1/1     Running   0          9s\nredis-follower-76c5cc5b79-g8vnf   1/1     Running   0          9s\nredis-leader-6666df964-vjhp2      1/1     Running   0          9s\n```\n\n查看 Service：\n```shell\nNAME             TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)        AGE\nfrontend         NodePort    10.106.145.169   \u003cnone\u003e        80:30693/TCP   24s\nkubernetes       ClusterIP   10.96.0.1        \u003cnone\u003e        443/TCP        4m58s\nredis-follower   ClusterIP   10.108.30.112    \u003cnone\u003e        6379/TCP       24s\nredis-leader     ClusterIP   10.106.255.152   \u003cnone\u003e        6379/TCP       24s\n```\n\n浏览器访问：http://localhost:30693\n\n网页上会显示出 Guestbook 的表单页面。\n\n更新 CR：\n\n```shell\n# 修改frontend 和 redis 副本数\nkubectl patch guestbook guestbook-sample -p '{\"spec\":{\"frontendSize\": 3, \"redisFollowerSize\": 3}}' --type=merge\n```\n\n查看 Pod：\n```shell\nNAME                              READY   STATUS    RESTARTS   AGE\nfrontend-85595f5bf9-4pmfj         1/1     Running   0          4s\nfrontend-85595f5bf9-jrcp4         1/1     Running   0          50s\nfrontend-85595f5bf9-q8fkl         1/1     Running   0          50s\nredis-follower-76c5cc5b79-bxbb4   1/1     Running   0          4s\nredis-follower-76c5cc5b79-fxxlq   1/1     Running   0          50s\nredis-follower-76c5cc5b79-g8vnf   1/1     Running   0          50s\nredis-leader-6666df964-vjhp2      1/1     Running   0          50s\n```\n\n### 做好清理\n\n```shell\noperator-sdk cleanup guestbook-operator\noperator-sdk olm uninstall\n```\n\n### 更多\n\n更多经典示例请参考：https://github.com/jxlwqq/kubernetes-examples\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjxlwqq%2Fguestbook-operator","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjxlwqq%2Fguestbook-operator","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjxlwqq%2Fguestbook-operator/lists"}