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

Kubernetes挂载ConfigMap为文件后Java读取遇找不到文件异常求助

问题解决步骤

一、修正Deployment挂载配置

你的Deployment配置里volumeMounts缩进错误,它属于containers下的容器配置块,不能和containers同级。修正后的核心配置片段如下:

apiVersion: apps/v1
kind: Deployment
metadata:
  ...
spec:
  ...
  template:
    metadata:
      labels:
        app: demo
      name: demo
    spec:
      containers:
      - image: abc:1.0
        imagePullPolicy: Always
        name: demo
        resources:
          limits:
            cpu: 500m
            memory: 650Mi
          requests:
            cpu: 500m
            memory: 650Mi
        # 修正:volumeMounts放置在当前容器的配置条目下
        volumeMounts:
        - mountPath: /opt/config/application_config.properties
          subPath: application_config.properties
          name: application-config-volume           
      volumes:
      - name: application-config-volume
        configMap:
          name: yml-config

若要更精准指定ConfigMap中的目标文件,可给configMap添加items字段(可选):

volumes:
- name: application-config-volume
  configMap:
    name: yml-config
    items:
    - key: application_config.properties
      path: application_config.properties

二、Java读取配置文件代码

使用Java标准库的Properties类读取指定路径的配置文件,代码示例:

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

public class ConfigReader {
    public static void main(String[] args) {
        // 挂载的配置文件绝对路径
        String configFilePath = "/opt/config/application_config.properties";
        Properties configProps = new Properties();
        
        try (FileInputStream inputStream = new FileInputStream(configFilePath)) {
            configProps.load(inputStream);
            
            // 读取配置项示例
            String id = configProps.getProperty("id");
            String mode = configProps.getProperty("mode");
            String username = configProps.getProperty("username");
            String endpoint = configProps.getProperty("endpoint");
            String url = configProps.getProperty("url");
            
            // 输出或使用配置值
            System.out.println("读取到id: " + id);
            System.out.println("读取到mode: " + mode);
        } catch (IOException e) {
            System.err.println("配置文件读取失败:" + e.getMessage());
            e.printStackTrace();
        }
    }
}

格式修正提示

你的ConfigMap中endpoint字段用了冒号endpoint: abc,标准properties文件应使用等号endpoint=abc,建议修正ConfigMap内的格式,避免读取异常。

三、无容器权限下的排查要点

  • 验证ConfigMap存在性:执行kubectl get configmap yml-config,确认data字段包含application_config.properties
  • 确认Deployment更新完成:执行kubectl rollout status deployment/<你的Deployment名称>,确保滚动部署无异常
  • 检查Pod事件:执行kubectl describe pod <目标Pod名称>,查看Events栏是否有挂载相关错误(如ConfigMap不存在、目录缺失)
  • 确认镜像内目录存在:若镜像未包含/opt/config目录,需在Dockerfile中添加RUN mkdir -p /opt/config指令

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 00:36:27