部署过程:K8s 三节点环境搭建 | Regen

​ 初次体验k8s,起了几个简单的pods、service、deployment

K8s pods service deployment初体验

pods

image-20250804171629285

busybox-pod

yaml文件:

  1. busybox-pod.yaml
1
2
3
4
5
6
7
8
9
10
11
12
apiVersion: v1
kind: Pod
metadata:
name: busybox
spec:
containers:
- name: busybox
image: registry.aliyuncs.com/google_containers/busybox:latest
command: ["sleep", "3600"] # 防止容器立即退出



nginx-pod

  1. nginx-pod.yaml
1
2
3
4
5
6
7
8
9
apiVersion: v1
kind: Pod
metadata:
name: my-nginx
spec:
containers:
- name: nginx
image: nginx:latest
imagePullPolicy: IfNotPresent

起容器的命令:

1
kubectl apply -f nginx-pod.yaml

image-20250804171629285

service

nginx-service

​ 上面起来了一个nginx pods,但是要怎么访问呢?—通过service

nginx-service.yaml :

1
2
3
4
5
6
7
8
9
10
11
12
13
apiVersion: v1
kind: Service
metadata:
name: my-nginx-service
spec:
type: NodePort
selector:
run: my-nginx
ports:
- protocol: TCP
port: 80 # Service 端口
targetPort: 80 # Pod 容器端口
nodePort: 30080 # 你访问的节点端口(30000-32767 之间)

部署service的命令:

1
kubectl apply -f nginx-service.yaml

再次之前需要先给之前的pod打上标签

查看标签的命令:

1
kubectl get pods --show-labels

image-20250804172606336

打标签的命令

1
kubectl label pod my-nginx run=my-nginx

如何查看service呢?

1
kubectl get svc

image-20250804172402282

然后就可以通过所有的机器的IP:30080访问同一个nginx容器了!

image-20250804173011788

image-20250804173054782

deployment

Nginx集群(service+扩缩容)

nginx-deployment.yaml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deployment # Deployment 的名字
spec:
replicas: 3 # 希望运行的 Pod 副本数
selector:
matchLabels:
app: nginx # 选择哪些 Pod 属于这个 Deployment(必须和 template 中 labels 一致)
template: # Pod 模板,Deployment 会根据这个模板创建 Pod
metadata:
labels:
app: nginx # 这个标签用于上面 selector 匹配
spec:
containers:

- name: nginx # 容器名字
image: nginx:latest # 使用的镜像
imagePullPolicy: Never
ports:
- containerPort: 80 # 容器暴露的端口

service.yaml

1
2
3
4
5
6
7
8
9
10
11
12
13
apiVersion: v1
kind: Service
metadata:
name: nginx-deployment-service
spec:
type: NodePort
selector:
app: nginx
ports:
- protocol: TCP
port: 80
targetPort: 80
nodePort: 30081

扩缩容:

1
kubectl scale deployment/nginx-deployment --replicas=5

好快的扩缩容

image-20250804173743514

问题

镜像源