IBM Cloud中Kubernetes部署Spring Boot连接MySQL数据源问题求助
Let's break down the issues preventing your Spring Boot app from connecting to the MySQL database in Kubernetes, and walk through the fixes step by step:
1. Core Issue: Incorrect Service Hostname in Data Source URL
In Kubernetes, pods communicate with each other using the Service's DNS name, not the Deployment name. Your MySQL Service is named mysqlservices, but your Spring config uses db (the Deployment name) as the hostname. This is why the connection fails—your app can't resolve db to the database service.
2. Fix the Data Source URL & Driver
Update your Spring datasource configuration to use the correct Service hostname and modern MySQL driver:
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" primary="true"> <!-- Use the updated MySQL driver for 5.7+ --> <property name="driverClassName" value="com.mysql.cj.jdbc.Driver" /> <!-- Replace 'db' with your Service name 'mysqlservices', add allowPublicKeyRetrieval to avoid common 5.7 connection errors --> <property name="url" value="jdbc:mysql://mysqlservices/nlfb?useSSL=false&allowPublicKeyRetrieval=true" /> <property name="username" value="*****" /> <property name="password" value="******" /> </bean>
If your app and MySQL are in different Kubernetes namespaces, use the full DNS name: mysqlservices.your-namespace.svc.cluster.local (replace your-namespace with the actual namespace name).
3. Critical Fix: Mismatched Volume/PVC Configuration
Your MySQL Deployment has two configuration mismatches that will prevent the database from starting at all:
- Volume name mismatch: The
volumeMountsreferencesmysql-persistent-storage, but thevolumesblock names the volumemypvc. These must match. - PVC name mismatch: The Deployment references
claimName: mysql-pv-claim, but your PVC is namedmypvc.
Fix the Deployment's volumes section to match:
volumes: - name: mysql-persistent-storage # Matches the volumeMounts name persistentVolumeClaim: claimName: mypvc # Matches your PVC's metadata.name
4. Verify Service & Pod Health
Before restarting your Spring Boot app, confirm the MySQL setup is healthy:
- Check if the MySQL pod is running:
kubectl get pods -l app=mysql,enviroment=test - Verify the MySQL Service is available:
You should see akubectl get service mysqlservicesClusterIPassigned to the service. - Test connectivity from your Spring Boot pod (exec into the pod first):
telnet mysqlservices 3306 # Or use nc if telnet isn't installed nc -zv mysqlservices 3306
5. Minor Cleanup: Typo in Label
You have a typo in your labels: enviroment instead of environment. While this works right now (since both Deployment and Service use the same typo), it's best to correct it to avoid confusion later.
Once you've applied these fixes, restart your Spring Boot Deployment, and the connection should work as expected.
内容的提问来源于stack exchange,提问作者Cosss

