spring - 在一个容器中运行 Spring Boot/PostgreSQL 应用程序
问题描述
我目前正在尝试在 Alpine/PostgreSQL 容器内构建 Spring Boot 应用程序,该应用程序将(在后期阶段)通过 Kafka 消息与其他 docker 容器通信。
在过去几天寻找解决方案后,我在这里发布了我的问题。我当前的问题是,我的容器在我尝试运行它时失败 - 我目前收到以下错误消息:
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.
[...]
Caused by: java.net.ConnectException: Connection refused (Connection refused)
[...]
org.springframework.jdbc.support.MetaDataAccessException: Could not get Connection for extracting meta-data; nested exception is org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection; nested exception is 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.
[...]
Caused by: org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection; nested exception is 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.
[...]
Caused by: 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.
[...]
Caused by: java.net.ConnectException: Connection refused (Connection refused)
所以看起来,Spring Boot 应用程序在数据库之前启动,因为在没有 ENTRYPOINT 命令的情况下运行图像并手动启动 .jar 文件可以正常工作。为了解决这个问题,我尝试了几种解决方案,例如
- 在 dockerfile 中使用 ENTRYPOINT 和 RUN 命令
- 编写等待脚本(如此处所述)
- 编写自定义 shell 脚本(见下框)
#!/bin/bash
sleep 3
sudo -u postgres postgres -D /var/lib/postgresql/data
sleep 3
java -jar persistence.jar
尝试第三种解决方案时出现以下异常:
postgres cannot access the server configuration file "/var/lib/postgresql/data/postgresql.conf": No such file or directory
所以最后,没有一个解决方案奏效。
设置
这是我的码头文件:
FROM postgres:9.3-alpine
ADD target/persistence-0.0.1.jar persistence.jar
ADD init-container.sh init-container.sh
ENV POSTGRES_DB test
ENV POSTGRES_USER test
ENV POSTGRES_PASSWORD password
RUN apk add --no-cache bash
RUN apk add sudo
RUN apk add openjdk8
ENTRYPOINT ["bash", "init-container.sh"]
这里是构建和运行命令:
docker build -t persistence .
docker run --name persistence -p 2002:2002 -d persistence
如果有人知道正确的解决方案,我将不胜感激!
谢谢你。
解决方案
推荐阅读
- python - 使用 URL 参数进行 REST API 搜索,测试使用某些值而不是其他值(都是有效条目)
- zsh-completion - 将 ZSH 配置为始终回退到路径完成
- django - 如何传递对象的主键以在 django 中应用 force_update?
- django - Django Rest Framework - response.set_cookie() 不在浏览器中设置 cookie,但在邮递员和可浏览 api 中工作
- javascript - 使用 .htaccess 重写 URL 但出现 404 错误
- reactjs - 首次使用“create-react-app my-app”创建 React 应用
- sonarqube - 如何从 Sonarcloud 问题中自动将问题添加到 GitHub 存储库
- javascript - 如何在使用另一个状态而不导致无限更新的情况下更新父级的状态?
- php - 根据搜索到的用户 ID 显示具有最新日期的结果
- python-3.x - 无法导入 colorama 模块