在 Kubernetes 上部署 Spring Boot 应用程序:应用程序使用环境变量中的错误端口属性

mar*_*gul 2 spring-boot kubernetes minikube

我正在尝试在 Kubernetes (Minikube) 上部署一个“Hello world”Spring Boot 应用程序。该应用程序非常简单,只有一种方法,映射到 GET 资源上。我什至没有指定端口。

我现在尝试在 Minikube 上部署该应用程序,并使用服务使其可用:

kind: Service
apiVersion: v1
metadata:
  name: server
spec:
  selector:
    app: server
  ports:
  - protocol: TCP
    port: 8080
  type: NodePort
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: server
spec:
  selector:
      matchLabels:
        app: server
  replicas: 3
  template:
    metadata:
      labels:
        app: server
    spec:
      containers:
        - name: server
          image: kubernetes-server:latest
          imagePullPolicy: Never
          ports:
            - name: http
              containerPort: 8080
Run Code Online (Sandbox Code Playgroud)

如果我使用此配置启动部署(即先启动服务,然后启动部署),Pod 在启动过程中会失败。在日志中,我可以找到以下消息:

***************************
APPLICATION FAILED TO START
***************************

Description:

Binding to target         
org.springframework.boot.autoconfigure.web.ServerProperties@42f93a98 failed:

    Property: server.port
    Value: tcp://10.98.151.181:8080
    Reason: Failed to convert property value of type 'java.lang.String' to required type 'java.lang.Integer' for property 'port'; nested exception is org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.lang.String] to type [java.lang.Integer]
Run Code Online (Sandbox Code Playgroud)

注意:10.98.151.181 是服务的集群 IP,如 Minikube 仪表板中所示。

如果我首先触发实际的部署,应用程序将成功启动,之后我可以启动服务。不过官方文档建议先启动服务,然后再部署:https://kubernetes.io/docs/concepts/configuration/overview/#services

对我来说,服务似乎将属性server.port设置为环境变量,而在服务之后启动的 Spring Boot 应用程序意外地将其解释为 Spring server.port

有什么想法如何解决这个问题吗?

mda*_*iel 7

对我来说,服务似乎将属性 server.port 设置为环境变量

不,kubernetes 它暴露了“docker 兼容”链接环境变量,因为你的Service名字是server,最终是SERVER_PORT=tcp://thing:8080因为它试图“有帮助”

解决方案是给你Service一个更具描述性的名称,或者屏蔽有问题的环境变量:

containers:
- name: server
  env:
  - name: SERVER_PORT
    value: ''  # you can try the empty string,
    # or actually place the port value with
    # value: '8080'
    # ensure it is a **string** and not `value: 8080`
Run Code Online (Sandbox Code Playgroud)