H2 DB in docker container

2019-08-30 23:06发布

问题:

I am running a very basic spring boot app in an alpine docker container with in memory H2 database on AWS. Unfortunately, webAllowOthers is not set, so i cannot access the H2 console.

Is there any way to access the data in the db?

I can sh into the container, but i dont know how to continue.

回答1:

Ok, I managed to solve it, in case anybody needs it in the future:

The H2 console has a tool to back up any DB to a .sql file ( accessible in the TOOLS menu ), but since the in memory DB only exists in the running process, it cannot be accessed with H2 Shell, only through the Console which is embedded in the spring boot app.

The H2 Console uses a lot of javascript, so in a command-line-only environment it was almost impossible to use it with command-line browsers ( felt like using VI for the first time... ), but checking how a locally running, accessible console works, gave the answer:

The Script tool uses the following request argument format (change it according to your config):

tool: Script
args: -url,jdbc:h2:mem:testdb,-user,sa,-script,~/backup.sql

So to backup the db:

  • sh into the container
  • wget http://localhost:8080/h2. The HTML source will have a link to login.jsp?jsessionid=xxxxx. Use this session ID in the curl command.
  • Post the needed data to the Script tool in an URL encoded format:
curl -d "tool=Script&args=-url%2Cjdbc%3Ah2%3Amem%3Atestdb%2C-user%2Csa%2C-script%2C%7E%2backup.sql" -H "Content-Type: application/x-www-form-urlencoded" -X POST http://localhost:8080/h2/tools.do?jsessionid=xxxx

If you did everything right, the backup SQL should be in the given place.