Search code examples
postgresqldockerdocker-composeknex.js

Knex Migration with Docker Compose Psql


I have a problem migrating using Knex js inside my docker-compose container. the problem is that npm run db (knex migrate:rollback && knex migrate:latest && knex seed:run) would run right before the database is even created. Is there anyway to say that I would only like to run npm run db after the database has been created?

NOTE : if I do this npm commands on the docker terminal after it has been built everything works fine. just fyi

here is my docker-compose.yml

version: '3.6'

services:
  #Backend api
  server:
    container_name: server
    build: ./
    command: npm run db
    working_dir: /user/src/server
    ports:
      - "5000:5000"
    volumes:
      - ./:/user/src/server
    environment:
      POSTGRES_URI: postgres://test:[email protected]:5432/interapp
    links:
      - postgres

  # PostgreSQL database
  postgres:
    environment:
      POSTGRES_USER: test
      POSTGRES_PASSWORD: test
      POSTGRES_DB: interapp
      POSTGRES_HOST: postgres
    image: postgres
    ports:
      - "5432:5432"

and here is my Dockerfile

FROM node:10.14.0

WORKDIR /user/src/server

COPY ./ ./

RUN npm install

CMD ["/bin/bash"]

Solution

  • on the docker-compose.yml file, using sh (bash) for a contained environment context for your command to run in. ie. sh -c 'npm run db' your docker-compose file would now be secondly, use the depends_on step to wait for the database to start

    services:
      #Backend api
        server:
        container_name: server
        build: ./
        command: sh -c 'npm run db'
        working_dir: /user/src/server
      depends_on:
        -postgres
      ports:
        - "5000:5000"
      volumes:
        - ./:/user/src/server
      environment:
        POSTGRES_URI: postgres://test:[email protected]:5432/interapp
      links:
        - postgres