在Docker中时,Spring Boot数据库连接不起作用 [英] Spring Boot database connection does not work when in Docker
问题描述
我有一个SpringBoot应用程序,可以在Tomcat上完美运行,并连接到Postgres数据库。
I have a SpringBoot application, that runs perfectly on Tomcat and connects to a Postgres database.
例如 application.properties
# approval datasource
spring.datasource2.driver-class-name=org.postgresql.Driver
spring.datasource2.jdbc-url=jdbc:postgresql://localhost:5432/approval
spring.datasource2.username=postgres
spring.datasource2.password=
接下来,我对应用程序进行了Docker化:
Next I have Dockerised the application:
Dockerfile
FROM openjdk:14
ARG JAR_FILE=target/*.jar
COPY ${JAR_FILE} nexct-approval-service.jar
EXPOSE 8081
ENTRYPOINT ["java","-jar","/nexct-approval-service.jar"]
我可以在应用程序中访问静态服务,但是它给出以下错误:
I can access a restful service in the application, however it is giving the following error:
org.postgresql.util.PSQLException: Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
一切都在 localhost
上运行,我计划将其部署到
Everything is running on localhost
and I plan to deploy this to a linux server where everying runs on the same host too.
问题
为什么docker似乎改变了主机访问?我该如何配置它以便它可以使用docker访问数据库?
Why does docker seem to change the host access? How do I configure this so that it can access the database using docker?
推荐答案
Mac解决方案:在Docker容器内部,只需将数据库主机设置为 host.docker.internal
。这将转发到运行Docker容器的主机。 参考
Solution for Mac: Inside your docker container simply have the db host set to host.docker.internal
. This will be forwarded to the host the docker container is running on. Reference
Linux解决方案:
实际上,实际上,您真正需要做的是将容器与在主机系统上运行的Postgres连接起来,因此我们需要告诉Docker将网络模式设置为主机。
Solution for Linux: Actually what you really need to do is connect your container with Postgres running on host system, so for that we need to tell Docker to set network mode to host.
docker run -it --network=host -p 8081:8081 --name containerName 'imageName'
或者使用 docker-compose.yml
:
要启动容器,只需执行以下命令 docker-compose up
To start the containers just issue following command docker-compose up
version: '3.7'
services:
configurator:
container_name: 'nameOfContainer'
image: 'imageName'
network_mode: "host"
ports:
- "8081:8081"
restart: on-failure
如需进一步了解,请遵循文档。
For further learning please follow the docs.
这篇关于在Docker中时,Spring Boot数据库连接不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!