我在學習docker並嘗試將使用Tomcat的Java Web應用程序放到容器中。我跟着一些基本的教程,但我發現沒有解決方案能夠正常工作給我。如果我跑我的數據庫和Java容器出現錯誤:無法使用Docker將Java程序連接到MySQL
SEVERE: Unable to create initial connections of pool.
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:981)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:339)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2253)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2286)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2085)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:795)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:44)
MySQL的Dockerfile
FROM mysql:latest
ENV MYSQL_DATABASE=db_name #name of db that is required by Java program
運行方式:
docker run --name db_name -e MYSQL_ROOT_PASSWORD=root -d db_name
的Java Dockerfile
FROM tomcat:7.0.70-jre8
ADD deploy /usr/local/tomcat/webapps #extracted .war
ADD jdbc /usr/local/tomcat/lib #MySQL jdbc drivers
ADD context /usr/local/tomcat/conf #context.xml
通過運行:
docker run --name app_name --link db_name:db_name -p 8080:8080 -d app_name
當我在Eclipse中本地運行它時,整個配置正常運行。
什麼是mysql_hostname或mysql連接字符串到java配置文件中? –
有 「URL =」 的jdbc:mysql的://本地主機:3306/DB_NAME」我改 「的jdbc:mysql的:// DB_NAME:3306/DB_NAME」 像@Ohmen建議和它的工作現在可以正確 – Marcon