1. 准备应用程序和环境
准备两个小型仓库,以及手动构建所需的访问权限。在本教程结束时,您将拥有可用于构建的源代码和一份完整的环境检查清单。现在还不需要部署应用程序或审批发布。
前提条件:完成 快速入门,并确保有管理员负责完成以下由平台负责的步骤。
1. 管理员:准备 CI 环境
使用一个新的练习命名空间,例如 cicd-tutorial,作为
<pipeline-namespace>。在示例中始终一致地替换占位符;不要将全局 kubectl
上下文切换到生产命名空间。
请参阅 ArtifactHub Shim 安装
以及 Hub 解析器,了解目录设置。
示例从 catalog: catalog 解析 git-clone:0.9、nodejs:0.1、golang:0.1 和
buildah:0.10,并使用 type: artifact 和 kind: task。
请确认这些版本存在于您安装的快照中。
WARNING
默认目录中的 Buildah Task 要求可用的非 root 用户命名空间。
如果节点禁用了这些命名空间,管理员必须选择已批准的替代
Task,以及任何所需的命名空间例外。仅替换 builderImage 并不会
更改 Task 的安全上下文。不要仅为了运行本教程而禁用 Pod Security 控制。
请参阅 Pod Security Restricted。
镜像镜像并配置信任
在 Pipeline 示例和 Containerfile 中填入 <internal-...-image> 占位符,使用已批准且通过摘要固定的内部引用。镜像目录工具镜像,这些镜像可能包含辅助程序,而不仅仅是普通的 Node.js 或 Go 基础镜像。Node.js 示例需要版本 22 或更高版本;Go 示例需要版本 1.23 或更高版本。
Task Pod 和节点镜像拉取器都必须能够访问并信任该注册表。仅能从 Pod 内部正常工作的地址不足以用于 Deployment 镜像。使用平台的常规工作流配置内部 CA 信任和私有镜像拉取凭据。保持启用 TLS 验证。
该应用程序没有第三方依赖项。首次 CI 运行不需要 package Connector。对于实际项目,请在添加依赖项之前镜像软件包,并使用内部 NPM 或 Go 代理。在隔离网络环境中,不要将公共软件包访问作为变通方法启用。
选择 Connector,而不复制凭据
打开平台的 Connector 管理页面,然后选择或创建 Git 和 staging OCI Connector。验证其 Ready 状态、端点、仓库权限和信任配置。在 Pipeline 示例中仅记录其名称和命名空间。
请参阅 Git Connector
和 OCI Connector。
凭据保留在由 Connector 支持的 Secret 中,而不是 Pipeline 参数中。
2. 开发人员:创建两个最小化仓库
创建用于 frontend 和 backend 的空内部 Git 仓库,每个仓库都包含一个
main 分支。将下面相应的示例复制到仓库根目录。
这些文件仅使用 Node.js 和 Go 标准库,因此不需要公共软件包服务。
package.json:
{
"name": "application-cicd-frontend",
"private": true,
"type": "module",
"scripts": {
"test": "node --test server.test.mjs",
"lint": "node --check server.mjs",
"build": "node build.mjs",
"start": "node dist/server.mjs"
}
}
// server.mjs
import { createServer } from 'node:http';
import { readFileSync } from 'node:fs';
import { pathToFileURL } from 'node:url';
// page is the static document returned for the root route.
const page = readFileSync(new URL('./index.html', import.meta.url));
// handleRequest serves the page and the probes used by Kubernetes.
export function handleRequest(request, response) {
if (request.url === '/readyz' || request.url === '/healthz') {
response.writeHead(200, { 'Content-Type': 'text/plain' });
response.end('ok');
return;
}
if (request.url === '/') {
response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
response.end(page);
return;
}
response.writeHead(404, { 'Content-Type': 'text/plain' });
response.end('Not found');
}
// Start the listener only when this file is executed as the container command.
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
createServer(handleRequest).listen(8080, '0.0.0.0');
}
<!-- index.html -->
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>Application CI/CD Demo</title></head>
<body>
<h1>Application CI/CD Demo</h1>
<output id="message">Loading backend message...</output>
<script type="module">
// Fetch the backend through the same Ingress host.
// response is the HTTP response returned by the backend route.
const response = await fetch('/api/message');
// payload is the JSON body displayed in the page.
const payload = await response.json();
document.querySelector('#message').textContent = payload.message;
</script>
</body>
</html>
// build.mjs
import { copyFileSync, mkdirSync } from 'node:fs';
mkdirSync('dist', { recursive: true });
copyFileSync('server.mjs', 'dist/server.mjs');
copyFileSync('index.html', 'dist/index.html');
// server.test.mjs
import assert from 'node:assert/strict';
import { createServer } from 'node:http';
import { once } from 'node:events';
import test from 'node:test';
import { handleRequest } from './server.mjs';
// Check the handler without binding the application's fixed port.
test('frontend serves the page and probes', async (context) => {
// server uses an ephemeral port so this test can run beside other tests.
const server = createServer(handleRequest).listen(0, '127.0.0.1');
context.after(() => server.close());
await once(server, 'listening');
// address identifies the local test listener.
const address = `http://127.0.0.1:${server.address().port}`;
assert.equal((await fetch(address)).status, 200);
assert.equal((await fetch(`${address}/readyz`)).status, 200);
assert.equal((await fetch(`${address}/healthz`)).status, 200);
});
# Containerfile
FROM <internal-node-runtime-image>
WORKDIR /app
COPY --chown=65532:65532 dist/ ./
USER 65532
EXPOSE 8080
CMD ["node", "server.mjs"]
go.mod:
module example.com/application-cicd/backend
go 1.23.0
// cmd/server/main.go
package main
import (
"encoding/json"
"log"
"net/http"
"os"
"time"
)
// handler serves the API and the independent Kubernetes probes.
func handler() http.Handler {
// mux keeps API requests and probes on separate paths.
mux := http.NewServeMux()
mux.HandleFunc("/api/message", func(response http.ResponseWriter, request *http.Request) {
// message is supplied by the workload ConfigMap.
message := os.Getenv("APP_MESSAGE")
if message == "" {
message = "Hello from the Go backend"
}
response.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(response).Encode(map[string]string{"message": message})
})
// probe returns success without depending on the frontend or a registry.
probe := func(response http.ResponseWriter, request *http.Request) {
response.WriteHeader(http.StatusOK)
}
mux.HandleFunc("/readyz", probe)
mux.HandleFunc("/healthz", probe)
return mux
}
// main starts the single listener used by the container and its probes.
func main() {
// server is the single listener used by the container and its probes.
server := &http.Server{Addr: ":8080", Handler: handler(), ReadHeaderTimeout: 5 * time.Second}
log.Fatal(server.ListenAndServe())
}
# Containerfile
FROM <internal-static-image>
COPY --chown=65532:65532 bin/server /app/server
USER 65532
EXPOSE 8080
ENTRYPOINT ["/app/server"]
Node.js 仓库包含 package.json、server.mjs、
server.test.mjs、build.mjs、index.html 和 Containerfile。Go
仓库包含 go.mod、cmd/server/main.go 和 Containerfile。
不要将任一应用嵌套在额外的目录中。CI Tasks 从仓库根目录运行。
替换 Containerfile 基础镜像占位符,然后提交并推送源代码。记录每个克隆 URL 和完整的提交 SHA。不要将 dist/、
bin/、本地凭据或平台配置文件提交到应用程序
仓库中。
前端在端口 8080 上提供页面,并请求 /api/message。Go
后端提供该 API,并从其环境中读取 APP_MESSAGE。两个
组件都提供 /readyz 和 /healthz。
如果本地安装了 Node.js 和 Go,请运行教程 2 中所示的检查。你也可以
在 CI Tasks 中执行这些检查。
3. 记录运行配置
使用教程 2 中的 Pipeline 和 Run Template 示例填充
占位符。为每个组件固定以下值:
source Workspace 使用 volumeClaimTemplate:Tekton 会为每个 PipelineRun
配置一个新的 PVC。切勿将所有运行绑定到一个固定的源 PVC;一个克隆操作
可能会覆盖另一个运行的文件。emptyDir 可用于一个
Task Pod 内部的缓存,但无法将源文件从克隆 Task 传递到构建 Task。
Integration 注解会将 Git 和 OCI Connector 接口与
Task 参数和 Workspace 关联起来。在 Pipeline 和生成的 PipelineRun 上都保留该注解。
开始时使用提供的映射;将其调整为其他 Task 时,请参阅
Pipeline Integration。
4. 管理员:按需准备后续阶段
不要让这些发布功能阻塞首次 CI 运行:
教程 4 中的工作负载清单包含一个 ConfigMap、两个 Deployment、两个
Service 和一个 Ingress。Deployment 配置了就绪探针和存活探针、
资源请求和限制,以及非 root 安全设置。Ingress 会将 /
路由到前端,并将 /api 路由到后端。拉取和 TLS Secret
必须已存在;其中的值不会包含在内。
现在准备好这些值,但要在 CI 生成两个初始镜像摘要后,在教程 4 中应用该工作负载。
Kubernetes Connector 为 Task 提供部署访问权限;它不会替代节点的 registry 拉取凭据。
检查点
确认两个仓库的根目录中都包含最小源代码,Git 和 OCI Connector 均为 Ready,并且 CI
身份、目录、镜像和存储均可用。只有后续阶段的文件仍应包含未解析的占位符。
下一步:构建并运行组件 CI。