连接到Docker容器中的H2数据库 [英] Connecting to an H2 Database in a Docker Container
问题描述
我有一个基本的Spring Boot Data JPA项目.我要连接的h2数据库位于/tmp/customerdb.h2.db
.使用mvn spring-boot:run
运行应用程序时,一切正常.该应用程序连接到数据库,添加记录,并将添加的记录打印到控制台.
I have a basic Spring Boot Data JPA project. The h2 database that I'm connecting to is located at /tmp/customerdb.h2.db
. When running the application using mvn spring-boot:run
everything works fine. The application connects to the database, adds records, and prints the added records to the console.
然后我构建一个docker容器并运行它.码头工人文件看起来像这样:
I then build a docker container, and run it. The docker file looks like this:
FROM java:8
VOLUME /tmp
ADD jpa-docker-1.0.0.jar app.jar
RUN bash -c 'touch /app.jar'
ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar",/app.jar"]
运行容器时,出现以下错误:
When I run the container I get the following error:
2015-06-12 19:25:57.200 WARN 1 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 42102, SQLState: 42S02
2015-06-12 19:25:57.200 ERROR 1 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : Table "CUSTOMER" not found; SQL statement:
因此,看起来应用程序看不到数据库.连接URL如下所示:
spring.datasource.url=jdbc:h2:/tmp/customerdb
So it looks like the application can't see the database. The connection URL looks like this:
spring.datasource.url=jdbc:h2:/tmp/customerdb
正如我提到的,在docker容器外运行时,此方法工作正常.我假设Dockerfile VOLUME /tmp
中的行在容器内创建了/tmp
目录,以及其中包含的所有文件,因此可见数据库,但这似乎无法正常工作.有想法吗?
As I mentioned, this works fine when running outside the docker container. I'm assuming that the line in the Dockerfile VOLUME /tmp
creates the /tmp
directory inside the container, along with all the files it contains, such that the database is visible, but this seems like it's not working. Thoughts?
TIA, -好吧
推荐答案
您应使用docker 数据卷.运行容器时,请指定参数:
You should use docker data volumes. When running your container you specify the parameter:
-v <host folder>:<container folder>
通过这种方式,主机上的映射在容器内部
This way, the on the host machine is mapped, inside the container
例如:
docker run -v /tmp:/tmp -d yourcontainer
您在容器内的应用程序查找文件/tmp/customerdb.h2.db
,该文件实际上位于db文件实际存在的/tmp/customerdb.h2.db
主机上(通常,您可以在来宾和主机上使用不同的路径;在您的示例中恰好主机和来宾文件夹都位于同一位置"/tmp")
Your application inside the container looks for the file /tmp/customerdb.h2.db
, which actually is on the host at /tmp/customerdb.h2.db
where the db file actually exists (in general you could use different paths on the guest and the host; in your example it just happens that the host and guest folders are both on the same location "/tmp")
这篇关于连接到Docker容器中的H2数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!