Search code examples
javascriptnode.jsdockerdatabase-migrationknex.js

How to run knex migrations from Dockerfile or docker-compose


I have Dockerfile that works with API and MySQL database and it should do migrations:

FROM node

WORKDIR /api

COPY . .

RUN npm install

EXPOSE 3001

VOLUME [ "/api/node_modules" ]

CMD [ "npm", "start" ]

Also, there is a docker-compose file where I have database as a service:

  db:
    image: mysql
    container_name: database
    ports:
      - "3306:3306"
    environment:
      MYSQL_ROOT_PASSWORD: password
      MYSQL_PASSWORD: password
      MYSQL_DATABASE: testdb

The problem is, I don't know how to run migrations. Should I do it from docker-compose file or Dockerfile?

I was trying to do something like this in Dockerfile, but it doesn't seem to be working:

...
CMD [ "knex", "migrate:latest" ]
...

Or:

...
RUN knex migrate:latest
...

Solution

  • I solved this problem, probably in stupid way, but it works. So, what I did is just added this on my API container:

    restart: on-failure
    command: bash -c "npm run knex && npm run start"
    

    Now, it just restarts container until get connection to database and does all migrations.