使用Postgresql对Spring Boot App进行Docker化

时间:2016-03-25 08:24:53

标签: java postgresql docker spring-boot containers

我正在尝试为使用PostgreSQL作为数据库的Spring Boot应用程序创建一个Docker容器。我的目标是构建一个运行app和PostgreSQL的容器。我创建了一个Dockerfile,如下所示:

FROM ubuntu:15.10
LABEL version="1"

ADD app.jar app.jar
RUN bash -c 'touch /app.jar'

#  Install Java, Postgresql
......

USER postgres
RUN /etc/init.d/postgresql start &&\
    psql --command "CREATE USER test WITH SUPERUSER PASSWORD 'test';" &&\
        createdb -O test test

USER root
RUN echo "local all all trust" >> /etc/postgresql/9.4/main/pg_hba.conf
RUN echo "listen_addresses='127.0.0.1'" >> /etc/postgresql/9.4/main/postgresql.conf
RUN echo "localhost vspyfe-db" >> /etc/hosts
#Define working directory.
WORKDIR /data
# Add VOLUMEs to allow backup of config, logs and databases
VOLUME  ["/tmp", "/etc/postgresql", "/var/log/postgresql", "/var/lib/postgresql"]

# Define commonly used JAVA_HOME variable
ENV JAVA_HOME /usr/lib/jvm/java-8-oracle
COPY ./entrypoint.sh /
RUN chmod +x /entrypoint.sh
ENTRYPOINT  ["/entrypoint.sh"]
CMD ["bash", "/usr/lib/postgresql/9.4/bin/postgres", "-D", "/var/lib/postgresql/9.4/main", "-c", "config_file=/etc/postgresql/9.4/main/postgresql.conf"]

和entrypoint.sh是:

#!/bin/sh
/etc/init.d/postgresql start
java -Djava.security.egd=file:/dev/./urandom -jar /app.jar

我使用此命令docker build --rm=true -t vspyfe/base:v1 .构建,并且 当我使用此命令docker run -i -t vspyfe/base:v1运行图像时,我得到了例外

Caused by: org.postgresql.util.PSQLException: FATAL: role "test" does not exist
at org.postgresql.core.v3.ConnectionFactoryImpl.readStartupMessages(ConnectionFactoryImpl.java:471)
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:112)
at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:66)
at org.postgresql.jdbc2.AbstractJdbc2Connection.<init>(AbstractJdbc2Connection.java:125)
at org.postgresql.jdbc3.AbstractJdbc3Connection.<init>(AbstractJdbc3Connection.java:30)
at org.postgresql.jdbc3g.AbstractJdbc3gConnection.<init>(AbstractJdbc3gConnection.java:22)
at org.postgresql.jdbc4.AbstractJdbc4Connection.<init>(AbstractJdbc4Connection.java:32)
at org.postgresql.jdbc4.Jdbc4Connection.<init>(Jdbc4Connection.java:24)
at org.postgresql.Driver.makeConnection(Driver.java:393)
at org.postgresql.Driver.connect(Driver.java:267)

即使我尝试使用默认用户名和密码(postgres,postgres)创建测试数据库,但我得到了异常,说测试数据库不存在。我不明白我做错了什么。在Dockerfile中,我指定了我在application.properties文件中使用的每个参数。

1 个答案:

答案 0 :(得分:-1)

您是否检查了连接属性?我有一个弹簧启动应用程序的工作示例与postgres很好地工作。两者都在不同的容器中运行。请参阅:

Spring Boot + Postgres example, using the fabric8.io plugin

运行示例:

  

mvn clean package -DskipTests docker:stop docker:build docker:run