Docker - Use docker-compose to initialize database

When using docker-compose.yml to run your application, you will need to ensure that your database is initialized before it is ready.
Although it is expected of the application to manage it’s own database migrations and seeding there maybe occasions where additional setup might be required such as enabling a database plugin, managing users and granting permissions. For such operations, using a Dockerfile, you would COPY an initialize shell script or SQL file to /docker-entrypoint-initdb.d. Any .sh or .sql file present there would be executed upon container start.
But while using docker-compose.yml to run an official database image, you can avoid creating a separate Dockerfile for the database by using the volumes parameter for the database service:
version: "3"
services:
postgres:
image: postgres
environment:
POSTGRES_USER: username
POSTGRES_PASSWORD: password
POSTGRES_DB: postgres
volumes:
- ./docker/init.sql:/docker-entrypoint-initdb.d/init.sql
restart: always
And that’s it. Any SQL statements present in init.sql would be executed on container start.
P.S.: Using
POSTGRES_USERPOSTGRES_PASSWORDPOSTGRES_DBenvironment variables would automatically create the database and the user and also grant permissions.Note: Take care to append
IF NOT EXISTSto anyCREATEqueries to avoid errors.


