Run sequelize migrate on a Docker container

Asked

Viewed 960 times

-1

Hello!

I have my development environment set up in Docker.

package json.:

{
  "name": "teste_sequelize",
  "version": "1.0.0",
  "description": "teste do sequelize",
  "main": "app.js",
  "scripts": {
    "start": "clear && nodemon app.js"
  },
  "author": "eu",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.19.0",
    "consign": "^0.1.6",
    "ejs": "^3.0.1",
    "express": "^4.17.1",
    "express-validator": "^5.3.1",
    "moment": "^2.24.0",
    "mysql2": "^2.1.0",
    "sequelize": "^5.21.3"
  },
  "devDependencies": {
    "jest": "^24.9.0",
    "nodemon": "^1.19.2",
    "sequelize-cli": "^5.5.1"
  }
}

Dokerfile:

FROM node:alpine

WORKDIR /usr/app

COPY package*.json ./
RUN npm install

COPY . .

EXPOSE 1234

CMD [ "npm","start" ]

Docker-Compose.yml:

version: "3"

volumes:
    data:

services: 
    db:
        image: mysql:5.6
        ports:
          - "3306:3306"
        volumes:
          - data:/var/lib/mysql
        environment:
          - MYSQL_ROOT_PASSWORD=rafaesah
          - MYSQL_DATABASE=my_db
          - TZ=America/Bahia

    myadmin:
        image: phpmyadmin/phpmyadmin:latest
        ports:
          - 80:80
        environment:
          - PMA_ARBITRARY=1

    app: 
        build: .
        command: npm start
        depends_on: 
          - db
        ports: 
          - "1234:1234"
        expose:
          - "1234"
        links: 
            - db
            - myadmin
        volumes: 
            - .:/usr/app

config;database.js:

module.exports = {
  username: 'root',
  password: 'senha',
  database: 'my_db',
  host: 'db',
  port: '3306',
  dialect: 'mysql',
};

When I run npm start in the terminal, and access routes via express the connection is successful. But open another terminal and try npx sequelize db:migrate he accuses erro: getaddrinfo ENOTFOUND. If I change the host in config/database.js for localhost to migrate works.

How to configure to work migrate without having to change the host every time?

  • Can you verify the answer? Don’t forget to accept it if you are satisfied with it.

1 answer

0

The problem with running Migration on the terminal is that your computer does not know what it is my_db.

There are 2 alternatives to solve this

  • Add my_db to your operating system hosts file (do not recommend);
  • Run commands from a container.

To initialize your container with bash and run the migration command you can do something like:

docker run --entrypoint /bin/bash SUA_IMAGEM_DO_DOCKER npx sequelize db:migrate

Another option is to start the container in iterative mode:

docker run -it SUA_IMAGEM_DO_DOCKER /bin/bash

Browser other questions tagged

You are not signed in. Login or sign up in order to post.