How to create postgres database and run migration when docker-compose up

entrypoint.sh (in here I get createdb: command not found)

Running createdb in the nodejs container will not work because it is postgres specific command and it's not installed by default in the nodejs image.

If you specify POSTGRES_DB: pg_development env var on postgres container, the database will be created automatically when the container starts. So no need to run createdb anyway in entrypoint.sh that is mounted in the nodejs container.

In order to make sequelize db:migrate work you need to:

  • add sequelize-cli to dependencies in package.json
  • run npm install so it gets installed
  • run npx sequelize db:migrate

Here is a proposal:

# docker-compose.yml

version: '3'
services:
  db:
    image: "postgres:11.2"
    ports:
      - "5432:5432"
    volumes:
      - ./pgData:/var/lib/psotgresql/data
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD:
      POSTGRES_DB: pg_development

  app:
    working_dir: /restify-pg
    entrypoint: ["/bin/bash", "./entrypoint.sh"]
    image: node:10.12.0
    ports:
      - "3000:3000"
    volumes:
      - .:/restify-pg
    environment:
      DB_HOST: db

# package.json

{
  ...
  "dependencies": {
    ...
    "pg": "^7.9.0",
    "pg-hstore": "^2.3.2",
    "sequelize": "^5.2.9",
    "sequelize-cli": "^5.4.0"
  }
}
# entrypoint.sh

npm install
npx sequelize db:migrate
npm run dev