You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

执行kubectl apply报错:无法反序列化为[]v1.ServicePort类型

问题解决方法

核心错误原因

你遇到的错误是因为Service的ports字段要求为数组类型,但配置里写成了单个对象。Kubernetes规定Service的ports必须是端口列表,每个端口项需要用-开头标记为数组元素。

完整修正后的配置文件

以下是修复所有语法及逻辑错误后的YAML配置:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-sf
  labels:
    app: nginx-sf
spec:
  selector:
    matchLabels:
      app: nginx-sf-pod
  replicas: 3
  template:
    metadata:
      labels:
        app: nginx-sf-pod
    spec:
      containers:
      - name: 'nginx-sf-container'
        image: 'nginx:1.21.1-alpine'
        ports:
        - containerPort: 80
        command: ['sh', '-c', 'echo Hello Kubernetes from the Deployment! && sleep 3600']
        volumeMounts:
        - name: config-volume
          mountPath: '/etc/nginx/nginx.conf'
        - name: auth_basic
          mountPath: '/etc/nginx/conf.d/.htpasswd'
          readOnly: true
      volumes:
      - name: config-volume
        configMap:
          name: nginx.conf
      - name: auth_basic
        secret:
          secretName: auth-basic

---
kind: Service
apiVersion: v1
metadata:
  name: sf-webserver
spec:
  selector:
    app: nginx-sf-pod
  ports:
  - protocol: TCP
    port: 80
    targetPort: 80

关键修复点说明

  • Service的ports字段:添加-将端口配置转为数组元素,符合Kubernetes API规范。
  • Deployment的containers字段:容器配置属于数组,必须用-开头标识每个容器项。
  • volumeMounts字段:原配置重复定义了volumeMounts,改为数组形式包含两个挂载项。
  • volumes字段:卷配置是数组,每个卷项前添加-。
  • Service的selector修正:原配置selector匹配的是Deployment标签,改为匹配Pod的标签app: nginx-sf-pod,确保Service能正确关联到Pod。

验证命令

修复后重新应用配置:

kubectl apply -f ./sftest.yml

可通过以下命令检查资源状态:

  • 查看Deployment:kubectl get deployments nginx-sf
  • 查看Pod:kubectl get pods -l app=nginx-sf-pod
  • 查看Service:kubectl get service sf-webserver

内容的提问来源于stack exchange,提问作者mordgren

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 11:43:07