How to setup postgresql within a docker container (in virtualbox/ubuntu) and use it from within a spring boot application (I'm not using the official postgresql docker image).
Setup
- download and install virtualbox 5.2
- download an ISO image of ubuntu 16.04
- create a vm in virtualbox based on that ubuntu 16.04 iso
- within virtualbox/ubuntu, install jdk8 : sudo apt-get install openjdk-8-jdk
- within virtualbox/ubuntu, create JAVA_HOME environment variable and add it to the PATH :
- export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64
- export PATH=$PATH:$JAVA_HOME/bin - within virtualbox/ubuntu, install docker : I personnally followed the docker.com tutorial https://docs.docker.com/engine/install/ubuntu/
- within virtualbox/ubuntu, start a container that runs postgresql : sameersbn/postgresql:12-20200524 (this is not the official image but it does the job), run :sudo docker run --name postgresql -itd --restart always --publish 5432:5432 --volume postgresql:/var/lib/postgresql --env 'PG_TRUST_LOCALNET=true' --env 'PG_PASSWORD=postgres' --env 'DB_USER=thollem' --env 'DB_PASS=thollem' --env 'DB_NAME=mydatabase' sameersbn/postgresql:12-20200524 -c listen_addresses='*'
- within virtualbox/ubuntu, run the spring boot client to store data in that postgresql database : mvn spring-boot:run
- within virtualbox/ubuntu, to see the content in the postgresql database you can :
(a)rerun the application with 'mvn spring-boot:run' again
(b)use psql
(c)use dbeaver (I personnally use that)
bonus : access postgresql from the guest machine.
1) allow communication between guest and virtual machine : https://2buntu.com/articles/1513/accessing-your-virtualbox-guest-from-your-host-os/
2) edit the application.properties file : change spring.datasource.url value :
from spring.datasource.url=jdbc:postgresql://localhost:5432/postgres to spring.datasource.url=jdbc:postgresql://192.168.99.101:5432/postgres
some troubleshoot commands :
- java -version
- sudo service postgresql stop
- sudo docker stop postgresql
- sudo docker rm postgresql