I am trying to dockerize my server and db with docker compose. However, I cannot make the server connect to db when I try to run migration with Sequelize. Below are my Dockerfile and docker-compose.yml:
Dockerfile:
FROM node:14-alpine
RUN mkdir -p /app
WORKDIR /app
ADD . /app
RUN yarn install
RUN yarn sequelize db:migrate
EXPOSE 9000
CMD [ "yarn", "start" ]
docker-compose.yml:
version: "3"
services:
db:
image: postgres:10
container_name: "postgres"
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: mydatabase
ports:
- '5432:5432'
volumes:
- my-db:/var/lib/postgresql/data
server:
build:
context: .
environment:
DB_USER: postgres
DB_PASSWORD: postgres
DB_NAME: mydatabase
depends_on:
- db
ports:
- 8100:8100
volumes:
my-db:
And here is the error log while doing the migration:
ERROR: connect ECONNREFUSED 127.0.0.1:5432
error Command failed with exit code 1.
I already try the suggestions from here, but change the db url cannot solve my issue. It returns
ERROR: getaddrinfo ENOTFOUND postgres://username:pgpassword@127.0.0.1:5432/mydatabase
(I already change the username, password, and db name).
Could someone figure out what goes wrong and how to fix this?
UPDATE: I try to change DB_URL to db which is same as the service name of db. Then the docker runs successfully. The idea came from the setup in this post.