首页 > 解决方案 > 在一个容器中运行 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 文件可以正常工作。为了解决这个问题,我尝试了几种解决方案,例如

  1. 在 dockerfile 中使用 ENTRYPOINT 和 RUN 命令
  2. 编写等待脚本(如此所述)
  3. 编写自定义 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

如果有人知道正确的解决方案,我将不胜感激!

谢谢你。

标签: springpostgresqlspring-bootdocker

解决方案


推荐阅读