Run Postgres migration with Docker/Docker compose Run Postgres migration with Docker/Docker compose docker docker

Run Postgres migration with Docker/Docker compose


I couldn't test this, but here's the idea:

  • have a docker-entrypoint.sh script in the same folder as Dockerfile
#!/usr/bin/env bash./node_modules/.bin/node-pg-migrate upexec "$@"
  • change Dockerfile to use that script
FROM docker_serviceENV NODE_ENV TESTWORKDIR /usr/src/appRUN npm install --only=devCOPY docker-entrypoint.sh /usr/local/bin/RUN chmod 777 /usr/local/bin/docker-entrypoint.sh && \    ln -s usr/local/bin/docker-entrypoint.sh / # backwards compatENTRYPOINT ["docker-entrypoint.sh"]EXPOSE 1337CMD ["npm", "run", "test"]

This way the docker-entrypoint.sh script will be executed every time you create container and will execute npm run test afterwards because of exec "$@". Every DB image has this kind of setup and I advise you to take a look at the PostgreSQL Dockerfile and entrypoint script.


You might need something like wait-for-it to make sure the DB has started, before executing migration scripts. depends_on helps you with start order but doesn't wait for the service to be healthy.

Resource: Control startup and shutdown order in Compose