I want to deploy a web application using Docker and docker-compose. To start with, I'm just focusing on the interaction between the PostgreSQL database and the Spring back-end. By following some tutorials I ended up with the following docker-compose.
version: "3"
services:
app:
image: 'first-docker-image:latest'
build:
context: ./backend
dockerfile: Dockerfile
container_name: app
depends_on:
- dbpostgresql
ports:
- 8080:8080
dbpostgresql:
image: postgres:12.9
container_name: dbpostgresql
environment:
- POSTGRES_USER=appuser
- POSTGRES_PASSWORD=admin
- POSTGRES_DB=app_db
ports:
- 5432:5432
The Dockerfile inside the backend directory calls the jar for to start my Spring back-end, and works fine. Also, a connection is made to the database 'app_db'.
The only problem that remains is the fact that this database is empty, so all API calls result in errors, as there are no tables or data in the database. I do however have an PostgreSQL dump (app_dump.bak) that I want to use to initialize this database.
To fix my problem, I can run the docker-compose and after the containers are up, I copy the data dump into the container like this.
sudo docker cp app_dump.bak <DOCKER_ID>:/app_dump.bak
After this I can create a shell inside the container and restore the dump by doing
pg_restore --no-owner --no-privileges -d app_db -U appuser app_dump.bak
And after doing this, everything works. I can make API calls to the back-end and the corresponding results are shown.
I'm looking for a way to do this procedure (initializing the database) when running docker-compose, so no extra steps are needed after the containers are up. Is there any way to specify this behavior inside the docker-compose set-up?
I'm quite new to Docker, so any pointers would be greatly appreciated.
CodePudding user response:
You can specify an init container which will mount your file and run the command;
version: "3"
services:
app:
image: "first-docker-image:latest"
build:
context: ./backend
dockerfile: Dockerfile
container_name: app
depends_on:
- dbpostgresql
ports:
- 8080:8080
dbpostgresql:
image: postgres:12.9
container_name: dbpostgresql
environment:
- POSTGRES_USER=appuser
- POSTGRES_PASSWORD=admin
- POSTGRES_DB=app_db
ports:
- 5432:5432
dbpostgresql_init:
image: postgres:12.9
container_name: dbpostgresql_init
command: pg_restore -h dbpostgresql --no-owner --no-privileges -d app_db -U appuser app_dump.bak
volumes:
- ./app_dump.bak:/app_dump.bak
environment:
- POSTGRES_USER=appuser
- POSTGRES_PASSWORD=admin
- POSTGRES_DB=app_db
depends_on:
dbpostgresql:
condition: service_started