I am new to Docker and was wondering how I should run my migrations. I’m using the following Dockerfile for my Node js backend
FROM node:14.16.0-alpine3.13
RUN addgroup app && adduser -S -G app app
USER app
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3001
RUN npm run db:up
CMD ["npm", "start"]
npm run db:up
just runs my migrations using migrate-mongo up
I also have a frontend and db that use a compose.yml file to run all my containers. Below is my compose.yml file.
services:
web:
depends_on:
- api
build: ./frontend
ports:
- 3000:3000
develop:
watch:
- path: ./frontend/package.json
action: rebuild
- path: ./frontend/package-lock.json
action: rebuild
- path: ./frontend
target: /app
action: sync
api:
depends_on:
- db
build: ./backend
ports:
- 3001:3001
environment:
DB_URL: mongodb://db/vidly
develop:
watch:
- path: ./backend/package.json
action: rebuild
- path: ./backend/package-lock.json
action: rebuild
- path: ./backend
target: /app
action: sync
db:
image: mongo:latest
ports:
- 27017:27017
volumes:
- vidly:/data/db
volumes:
vidly:
I’m getting the error
=> ERROR [api 7/7] RUN npm run db:up 33.0s
------
> [api 7/7] RUN npm run db:up:
0.889
0.889 > [email protected] db:up /app
0.889 > migrate-mongo up
0.889
32.90 ERROR: connect ECONNREFUSED 127.0.0.1:27017 MongoServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
32.90 at Timeout._onTimeout (/app/node_modules/migrate-mongo/node_modules/mongodb/lib/sdam/topology.js:292:38)
32.90 at listOnTimeout (internal/timers.js:554:17)
32.90 at processTimers (internal/timers.js:497:7)
32.94 npm ERR! code ELIFECYCLE
32.94 npm ERR! errno 1
32.95 npm ERR! [email protected] db:up: `migrate-mongo up`
32.95 npm ERR! Exit status 1
32.95 npm ERR!
32.95 npm ERR! Failed at the [email protected] db:up script.
32.95 npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
32.96
32.96 npm ERR! A complete log of this run can be found in:
32.96 npm ERR! /home/app/.npm/_logs/2024-06-17T16_51_27_332Z-debug.log
------
when I try to run docker-compose up
.
This error means that mongod
isn’t running yet and therefore the migration fails. At least I think so. I thought by setting depends_on=db
on my compose.yml file, my backend service would only run once mongod is executed, but that doesn’t seem to be the case.
My question is how would I ensure my migrations get run after mongod is executed?