gpt4 book ai didi

docker - docker-compose无法访问数据库端口

转载 作者:行者123 更新时间:2023-12-02 20:01:39 26 4
gpt4 key购买 nike

dockerfile:

FROM anapsix/alpine-java:8_server-jre_unlimited
# copy application
COPY server.jar /opt/test/
COPY application.yml /opt/test/

# expose server ports
EXPOSE 8080 18080

# Run via dumb-init
WORKDIR /opt/test
ENTRYPOINT ["java"]
CMD ["-jar", "server.jar"]

docker-compose文件:
services:
backend-server:
image: test.com/server:latest
build: .
depends_on:
- database-server
ports:
- "127.0.0.1:8080:8080"
- "127.0.0.1:18080:18080"
database-server:
image: postgres:9.6
ports:
- "127.0.0.1:5432:5432"
environment:
- POSTGRES_PASSWORD testtest

应用程序属性文件:
spring:
datasource:
# use default user/database created by PostgreSQL Docker image upon startup
url: jdbc:postgresql://localhost/postgres
username: postgres
password: testtest
driver-class-name: org.postgresql.Driver

当我运行docker-compose时,它将创建一个数据库容器和一个连接到数据库容器的应用程序容器。

但是spring应用程序容器在启动过程中遇到了一些错误:

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.


docker container ls显示数据库正在运行,如果直接运行spring应用程序,则可以访问它。
a295bfd16e2c        postgres:9.6        "docker-entrypoint.s…"   About a minute ago   Up About a minute   127.0.0.1:5432->5432/tcp   server_database-server_1

那么我搞砸了什么问题呢?

解决方案,我找到
services:
backend-server:
image: test.com/server:latest
build: .
environment:
- SPRING_DATASOURCE_URL=jdbc:postgresql://database-server/postgres
depends_on:
- database-server
ports:
- 8080:8080
- 18080:18080
database-server:
image: postgres:9.6
ports:
- 5432:5432
environment:
- POSTGRES_PASSWORD testtest

但是我仍然无法从计算机的 localhost:8080访问该应用程序,即使容器的日志显示

2018-10-31 15:02:40.881 INFO 1 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''

2018-10-31 15:02:40.881 INFO 1 --- [ main] com.test.server.Application : Started Application in 12.823 seconds (JVM running for 13.235)

最佳答案

我建议按如下所示修改您的docker-compose.yml文件并进行测试

services:


backend-server:
image: test.com/server:latest
build: .
depends_on:
- database-server
ports:
- 8080:8080
- 18080:18080
database-server:
image: postgres:9.6
ports:
- 5432:5432
environment:
- POSTGRES_PASSWORD testtest

关于docker - docker-compose无法访问数据库端口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53084886/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com