构建自己的Helm Chart
一般常见的应用(nginx、wordpress等)公有的helm仓库都提供了chart,可以直接安装或者自定义安装。下面实践从零构建自己的helm chart应用。
准备工作
准备一个用于部署测试的应用镜像并推送到镜像仓库。
应用代码
这里使用python基于flask开发一个web服务器,该服务通过读取环境变量 USERNAME 获得用户自己定义的名称,然后监听 80 端口。对于任意 HTTP 请求,返回 Hello ${USERNAME}。比如如果设置USERNAME=world(默认场景),该服务会返回 Hello world。
创建app.py,内容如下:
from flask import Flask
import os
app = Flask(__name__)
@app.route("/", methods=["GET"])
def hello():
username = os.getenv("USERNAME", "world")
return f"Hello {
username}!"
if __name__ == "__main__":
app.run(host="0.0.0.0", port=80)
构建容器镜像
- 创建Dockerfile
# 使用官方 Python 基础镜像
FROM python:3.10-slim
# 设置工作目录
WORKDIR /app
# 复制当前目录内容到工作目录
COPY . /app
# 安装依赖
RUN pip install --no-cache-dir Flask -i https://mirrors.aliyun.com/pypi/simple/
# 设置环境变量
ENV USERNAME world
# 暴露应用运行的端口
EXPOSE 80
# 运行 Flask 应用
CMD ["python", "app.py"]
- 构建容器镜像
root@master1:~/hello# docker build -t my-hello .
- 将镜像推送到harbor
root@master1:~/hello# docker tag docker.io/library/my-hello:latest harbor.test.com/library/my-hello:v1.0
root@master1:~/hello# docker push harbor.test.com/library/my-hello:v1.0
在 Docker 构建好镜像之后,我们把镜像上传到仓库中,可以使私有镜像harbor,或者公有仓库比如 Docker Hub 或是阿里云容器镜像仓库。
构建应用的helm chart
应用的容器镜像已经构建推送到仓库,接下来我们创建应用的helm chart。
创建helm chart
使用以下命令创建一个新的 Helm Chart:
helm create my-hello
这个命令会生成一个名为 my-hello
的目录,里面包含了 Helm Chart 的基本结构。my-hello
目录的结构如下:
root@master1:~/hello# helm create my-hello
Creating my-hello
root@master1:~/hello# tree my-hello/
my-hello/
├── charts
├── Chart.yaml
├── templates
│ ├── deployment.yaml
│ ├── _helpers.tpl
│ ├── hpa.yaml
│ ├── ingress.yaml
│ ├── NOTES.txt
│ ├── serviceaccount.yaml
│ ├── service.yaml
│ └── tests
│ └── test-connection.yaml
└── values.yaml
需要注意的是,Chart 里面的 my-hello名称需要和生成的 Chart 文件夹名称一致。如果修改 my-hello,则需要做一致的修改。
编辑 Chart.yaml
在根目录下的 Chart.yaml 文件内,声明了当前 Chart 的名称、版本等基本信息,这些信息会在该 Chart 被放入仓库后,供用户浏览检索。
编辑 Chart.yaml
文件,定义 Chart 的元数据:
apiVersion: v2
name: my-hello
description: My hello app Helm chart for Kubernetes # helm chart描述信息
# A chart can be either an 'application' or a 'library' chart.
#
# Application charts are a collection of templates that can be packaged into versioned archives
# to be deployed.
#
# Library charts provide useful utilities or functions for the chart developer. They're included as
# a dependency of application charts to inject those utilities and functions into the rendering
# pipeline. Library charts do not define any templates and therefore cannot be deployed.
type: application
# This is the chart version. This version number should be incremented each time you make changes
# to the chart and its templates, including the app version.
# Versions are expected to follow Semantic Versioning (https://semver.org/)
version: 1.0 #Chart 的版本
# This is the version number of the application being deployed. This version number should be
# incremented each time you make changes to the application. Versions are not expected to
# follow Semantic Versioning. They should reflect the version the application is using.