Sha*_*014 5 postgresql docker spring-boot docker-compose
我正在构建我的第一个 Springboot 2.0 应用程序。我试图将我的 Springboot 应用程序放入一个 docker 容器,将我的 PostgresDB 放入另一个容器中。
我的 Dockerfile
FROM frolvlad/alpine-oraclejdk8:slim
VOLUME /tmp
ADD springboot-api-demo-0.1*.jar app.jar
RUN sh -c 'touch /app.jar'
EXPOSE 9443
ENTRYPOINT [ "sh", "-c", "java $JAVA_OPTS -Djava.security.egd=file:/dev/urandom -jar /app.jar" ]
Run Code Online (Sandbox Code Playgroud)
我的 docker-compose.yml 文件
version: "2.1"
services:
springboot-api-demo:
image: "fw/springboot-api-demo"
mem_limit: 1024m
ports:
- "8080:8080"
environment:
- SPRING_PROFILES_ACTIVE=local
- AWS_REGION=local
- ENVIRONMENT=local
- AUTH_ENABLED=false
postgres:
container_name: pgdb
image: postgres:9.6-alpine
environment:
- 'POSTGRES_ROOT_PASSWORD=postgres'
- 'POSTGRES_USER=postgres'
- 'POSTGRES_PASSWORD=postgres'
ports:
- "54321:5432"
Run Code Online (Sandbox Code Playgroud)
我在application.properties 中使用 Springboot JPA Data 2.0 和以下配置数据
spring.datasource.url= jdbc:postgresql://localhost:54321/java_learning
spring.datasource.username=postgres
spring.datasource.password=postgres
Run Code Online (Sandbox Code Playgroud)
我可以测试两个图像都已启动。同样从 docker log 和 docker events,我看到 postgres 容器运行良好,即使我可以访问它并且也创建了一个数据库。但是 springboot 容器启动了,但我死了,因为它无法连接到 postgress 并在下面抛出错误。
无法从数据库获取连接:连接尝试失败
请注意,我的主机已经在端口 5432 上安装了 Postgres,这就是为什么我在我的 postgres 容器上对 54321:5432 进行了端口映射。这是证明:) -
? springboot-api-demo git:(master) ? lsof -i:54321
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
com.docke 44345 shailendra.singh 18u IPv4 0xf62897fbdd69e31d 0t0 TCP *:54321 (LISTEN)
com.docke 44345 shailendra.singh 21u IPv6 0xf62897fbdd119975 0t0 TCP localhost:54321 (LISTEN)
? springboot-api-demo git:(master) ? lsof -i:5432
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
postgres 715 shailendra.singh 5u IPv6 0xf62897fbb43e03b5 0t0 TCP localhost:postgresql (LISTEN)
postgres 715 shailendra.singh 6u IPv4 0xf62897fbbaeea9bd 0t0 TCP localhost:postgresql (LISTEN)
Run Code Online (Sandbox Code Playgroud)
我不确定是什么问题。但是我的 Springboot 应用程序无法连接我的 postgres 容器,该容器使用适当的凭据运行良好。
尝试:
spring.datasource.url= jdbc:postgresql://pgdb:5432/java_learning
Run Code Online (Sandbox Code Playgroud)
postgres 数据库不在本地主机上运行,它在具有其他 IP(尚不知道)的另一个容器中运行。
值得庆幸的是,docker-compose 会自动创建一个在 docker-compose.yml 中的所有容器之间共享的网络(除非明确说明不要这样做),因此您可以神奇地使用服务名称作为主机名。
此外,您在端口中有一个错字,Postgres5432默认使用,而不是54321
| 归档时间: |
|
| 查看次数: |
8594 次 |
| 最近记录: |