Do you need to run some migration scripts on your Postgres database that is running in Docker? If you want to automate those migration scripts, it can be tricky because you don’t know when the Postgres instance has fully launched (you really only know when the Docker container is running).

If you are using the official Postgres image, you’re in luck – the image provides a way for you to run .sql and .sh files after Postgres has launched, and it evens executes them in alphabetical order!

The trick is to get all the .sql and .sh files onto the container instance, in the directory /docker-entrypoint-initdb.d. I’m sure there are lots of great ways to do this (and I know almost none of them), but in my case I did it via a docker-compose.yaml file. My solution consisted of mounting a host directory in the Postgres image via a docker-compose.yaml file, the relevant portion is below:

postgres:
  image: postgres:9.6
  ports:
    - '5432:5432'
  volumes:
    - c:\sql\:/docker-entrypoint-initdb.d/

In my case, all the .sql files that I wanted to run existed at c:\sql\.

For more information check out the offocial docs, specifically the section entitled How to extend this image.

I’m whaling because I can’t come up with a good Docker joke to end this post with….. :).