Kubernetes (K8s) 是一个用于自动化部署、扩展和管理容器化应用程序的开源平台。在K8s中,Service 和 Ingress 是两种用于暴露应用程序的方式。Service 用于在集群内部暴露应用程序,Ingress 则用于从集群外部访问应用程序。

## K8s Service 与 Ingress 整体流程

| 步骤 | 操作 |
| ------ | ------ |
| 1 | 创建 Deployment 部署应用程序 |
| 2 | 创建 Service 为应用程序创建服务 |
| 3 | 创建 Ingress 为应用程序创建路由 |

### 步骤一:创建 Deployment 部署应用程序

```yaml
# deployment.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
name: my-app
spec:
replicas: 3
selector:
matchLabels:
app: my-app
template:
metadata:
labels:
app: my-app
spec:
containers:
- name: my-app
image: my-app:latest
ports:
- containerPort: 80
```

- 解释:创建一个名为 my-app 的 Deployment,指定了运行容器的镜像和端口。

执行命令:

```bash
kubectl apply -f deployment.yaml
```

### 步骤二:创建 Service 为应用程序创建服务

```yaml
# service.yaml

apiVersion: v1
kind: Service
metadata:
name: my-app-service
spec:
selector:
app: my-app
ports:
- protocol: TCP
port: 80
targetPort: 80
type: ClusterIP
```

- 解释:创建一个名为 my-app-service 的 Service,与 Deployment 中的标签匹配,并将容器端口暴露出来。

执行命令:

```bash
kubectl apply -f service.yaml
```

### 步骤三:创建 Ingress 为应用程序创建路由

```yaml
# ingress.yaml

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: my-app-ingress
spec:
rules:
- host: my-app.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: my-app-service
port:
number: 80
```

- 解释:创建一个名为 my-app-ingress 的 Ingress,将 my-app.example.com 映射到 Service 上。

执行命令:

```bash
kubectl apply -f ingress.yaml
```

使用以上步骤,你就成功地将应用程序部署到了 Kubernetes 集群中,并通过 Service 和 Ingress 进行了暴露和路由。希望这篇文章对您有所帮助和启发!