I use postgres a lot both at work and in my personal projects. Recently I finally learned an easy way to set up the development environment for an application that uses postgres, utilizing docker-compose.
Overview
This is the directory structure of my project:
|
|
Both conf and data directories will be mounted into containers.
Compose file
I like using pgAdmin along with postgres to have a GUI for managing the development database.
|
|
pgAdmin config file
This file is used to automatically add a connection to the database upon startup of the pgAdmin container.
|
|
Database initialization scripts
The sql scripts under data
directory will be executed when the postgres container starts. The scripts are executed in alphabetical order, so in the above example, 001-schema.sql
will be executed before 002-data.sql
.
I usually have
001-schema.sql
for creating tables and indexes002-data.sql
for inserting initial data
Usage
To start the development environment, run:
|
|
pgAdmin will be available at http://localhost:5050 with the default email and password.
Update schema
One common situation is that you have done some changes to the schema via pgAdmin, and you want to persist the changes for future development sessions. To do this, you can use the pg_dump
command to dump the schema to a file:
|
|
Conclusion
I’ve been liking this method, and have been using it for multiple projects. It’s very easy to spin up the environment once you have the config files set up, and the whole environment can be version-controlled, making it very portable.