本文演示如何在 Kubernetes 集群 中,通过 Deployment + NodePort Service 部署并访问一个 Nginx 服务,适合 K8s 初学者内网测试环境


一、环境准备

在开始之前,请确保你已经满足以下条件:

  • Kubernetes 集群已搭建完成
    (至少 1 个 Master + 1 个 Node)
  • 已正确配置 kubectl,可正常访问集群
  • 节点网络、DNS 正常,能够拉取镜像

验证集群状态:

kubectl get nodes

二、创建 Nginx 部署文件

在任意节点上,新建一个 nginx-deploy.yaml 文件:

vim nginx-deploy.yaml

写入以下内容:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx
spec:
  replicas: 1                 # 副本数
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: docker.m.daocloud.io/nginx   # 使用 DaoCloud 镜像源
        imagePullPolicy: IfNotPresent
        ports:
        - containerPort: 80
---
apiVersion: v1
kind: Service
metadata:
  name: nginx
spec:
  type: NodePort               # 使用 NodePort 暴露服务
  selector:
    app: nginx
  ports:
  - port: 80                   # Service 内部端口
    targetPort: 80             # Pod 端口
    nodePort: 32737            # 节点对外端口(30000–32767)

配置说明

  • Deployment

    • replicas: 1:启动 1 个 Nginx Pod
    • containerPort: 80:容器内监听 80 端口
  • Service

    • type: NodePort:通过节点 IP + 端口访问
    • nodePort: 32737:对外暴露端口

三、部署 Nginx 到集群

执行以下命令创建资源:

kubectl apply -f nginx-deploy.yaml

查看资源状态:

kubectl get pods -o wide
kubectl get svc nginx

四、检查 Pod 运行状态

查看 Pod 是否正常运行:

kubectl get pods -o wide

示例输出:

NAME                     READY   STATUS    RESTARTS   AGE   IP             NODE
nginx-6776484bdd-9m4tj   1/1     Running   0          2m    10.100.104.13  node2

字段说明:

  • READY1/1 表示容器就绪
  • STATUSRunning 表示运行正常
  • IP:Pod 在集群内的 IP
  • NODE:Pod 所在的节点

五、检查 Service 暴露情况

查看 Nginx Service:

kubectl get svc nginx

示例输出:

NAME    TYPE       CLUSTER-IP     EXTERNAL-IP   PORT(S)        AGE
nginx   NodePort   10.99.58.214   <none>        80:32737/TCP   2m

说明:

  • CLUSTER-IP:集群内部访问地址

  • 80:32737/TCP

    • 集群内通过 80 端口访问
    • 集群外通过节点的 32737 端口访问

六、访问 Nginx 服务

获取任意一个 Node 节点 IP,例如:

192.168.31.34

1️⃣ 浏览器访问

http://192.168.31.34:32737

2️⃣ 命令行访问

curl http://192.168.31.34:32737

如果看到 Nginx 默认欢迎页面,说明部署成功 🎉


七、常见问题排查

1️⃣ 无法访问页面

  • 检查 Pod 是否 Running
  • 检查 Service 端口是否正确
  • 确认防火墙未拦截 NodePort 端口
kubectl describe svc nginx

2️⃣ 镜像拉取失败

可手动拉取镜像测试:

docker pull docker.m.daocloud.io/nginx
Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐