在stackoverflow上搜索后感觉这是一个常见的问题,但我没有发现这个决定。
如果没有docker,程序可以在本地运行。docker文件:
FROM openjdk:8
ADD target/DockerMyBlog.jar DockerMyBlog.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "DockerMyBlog.jar"]
应用程序。属性(尝试替换"localhost"这里<;dockermyblog":
jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/javastudy
jdbc.username=hey
jdbc.password=hey
在终端使用命令创建容器:
docker build -t dockermyblog .
尝试通过:
docker run -p 8080:8080 dockermyblog
收到一个错误:
com.mysql.cj.jdbc.exceptions.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 com.mysql.cj.jdbc.exceptions.SQLError.createCommunicationsException(SQLError.java:174)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:64)
at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:829)
at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:449)
......................
尝试设置(不理解那是什么):
jdbc:mysql://localhost:3306/javastudy?enabledTLSProtocols=TLSv1.2
或
jdbc.url=jdbc:mysql://dockermyblog:3306/javastudy?autoReconnect=true&useSSL=false
尝试输入终端:
docker inspect dockermyblog | grep IPAddress
终端不知道"grep">
我应该怎么做才能在本地启动
当您像这样在Java应用程序中使用localhost
时,它解析为容器上的地址,而不是主机上的地址(因此您的计算机)。因为没有MySQL服务器在同一个容器中运行,所以它会失败。
如果您将url更改为jdbc.url=jdbc:mysql://host.docker.internal:3306/javastudy
,则容器Java应用程序可以访问主机上运行的MySQL。
但是,要使它在本地运行(因此从Intellij和从容器)时都能工作,您可以使用不同的spring-boot配置文件。比如application-local.proeprties
,它只包含jdbc.url=jdbc:mysql://localhost:3306/javastudy
,如果你使用该配置文件,它将覆盖url