在Kubernetes (K8s) 中部署 Vue 前端镜像是一个常见的需求,本文将为刚入行的小白介绍实现这一过程的详细步骤和相应的代码示例。

## 1. 准备工作

在部署 Vue 前端镜像之前,需要确保以下几个条件已满足:
1. 安装 Docker:在本地环境或者部署 K8s 的服务器上安装 Docker,并确保 Docker 已正确配置。
2. 配置 K8s 环境:在部署 Vue 前端镜像之前,需要搭建好 K8s 的运行环境,包括 Master 节点和 Worker 节点。
3. 构建 Vue 前端镜像:在进行部署之前,需要先构建 Vue 前端项目的 Docker 镜像。

## 2. 部署 Vue 前端镜像

下面的步骤将指导你如何使用 K8s 部署 Vue 前端镜像:

### 步骤一:创建 Deployment

在 K8s 中,使用 Deployment 来定义需要运行的应用程序。下面的代码示例展示了一个 Deployment 的 YAML 文件,可以将其保存为 `deployment.yaml`:

```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: frontend-deployment
spec:
replicas: 3
selector:
matchLabels:
app: frontend
template:
metadata:
labels:
app: frontend
spec:
containers:
- name: frontend-container
image: your-dockerhub-username/frontend-image:tag
ports:
- containerPort: 80
```
代码说明:
- `metadata.name`:Deployment 的名称,这里被命名为 `frontend-deployment`。
- `spec.replicas`:指定副本数,这里设置为 3 个副本。
- `spec.selector.matchLabels`:通过标签选择器来选择需要管理的 Pod,这里选择了标签为 `app: frontend` 的 Pod。
- `spec.template.metadata.labels`:指定 Pod 的标签,与选择器中的标签匹配。
- `spec.template.spec.containers.image`:指定镜像名称,格式为 `your-dockerhub-username/frontend-image:tag`。
- `spec.template.spec.containers.ports.containerPort`:前端应用程序的监听端口。

### 步骤二:创建 Service

在 K8s 中,使用 Service 来公开部署的应用程序。下面的代码示例展示了一个 Service 的 YAML 文件,可以将其保存为 `service.yaml`:

```yaml
apiVersion: v1
kind: Service
metadata:
name: frontend-service
spec:
selector:
app: frontend
type: NodePort
ports:
- protocol: TCP
port: 80
targetPort: 80
nodePort: 30000
```
代码说明:
- `metadata.name`:Service 的名称,这里被命名为 `frontend-service`。
- `spec.selector`:通过标签选择器来选择需要公开的 Pod,这里选择了标签为 `app: frontend` 的 Pod。
- `spec.type`:指定 Service 的类型,这里设置为 `NodePort`,表示将 Service 以每个节点的 IP 地址和一个随机端口暴露出来。
- `spec.ports`:指定服务的端口映射配置,这里的配置表示将外部访问的 80 端口映射到 Pod 中的 80 端口。
- `spec.ports.nodePort`:指定 NodePort 的端口号,这里设置为 30000。

### 步骤三:部署 Vue 前端镜像

#### 使用 kubectl 命令行工具

在终端中使用 `kubectl` 命令行工具来部署 Vue 前端镜像,执行以下命令:

```shell
kubectl apply -f deployment.yaml
kubectl apply -f service.yaml
```
这将根据 YAML 文件创建 Deployment 和 Service。

#### 使用 Kubernetes Dashboard

如果 K8s 集群已配置好 Kubernetes Dashboard,你也可以通过可视化界面来部署 Vue 前端镜像。只需打开 Dashboard,点击 "Create" 按钮,选择 "Deployment",然后粘贴上述 Deployment 的 YAML 配置即可。接着同样的方式创建 Service。

### 步骤四:访问 Vue 前端应用

若部署成功,你将能够通过浏览器访问 Vue 前端应用。具体访问方式为:`http://Node-IP:NodePort`。

其中,`Node-IP` 是运行 Worker 节点的主机的 IP 地址,`NodePort` 是在 Service 的配置中指定的端口号(在上述示例中为 30000)。

## 总结

使用 K8s 部署 Vue 前端镜像的过程可以通过以下几个步骤总结:

1. 创建 Deployment:定义需要运行的应用程序的 Deployment 配置文件,并使用 kubectl 或 Kubernetes Dashboard 来创建 Deployment;
2. 创建 Service:定义需要公开的 Pod 的 Service 配置文件,并使用 kubectl 或 Kubernetes Dashboard 来创建 Service;
3. 访问应用程序:通过浏览器访问部署的 Vue 前端应用,使用 `http://Node-IP:NodePort` 的形式。

至此,你已经学会了使用 K8s 部署 Vue 前端镜像的过程。希望这篇文章对你有所帮助!