Mysql sequelize error in Docker

Asked

Viewed 721 times

0

I can’t connect the mysql api to Docker, but I can run mysql on Docker from the terminal

index js.

const db = require('../config/database');

const sequelize = new Sequelize(db)

module.exports = sequelize;

database js.

    database: 'mydb',
    username: 'mysql',
    password: 'pass',
    host: 'localhost',
    dialect: 'mysql'

}
sudo yarn sequelize db:create

returns ERROR: connect ECONNREFUSED 127.0.0.1:3306

server.js running express is configured for port 3001

2 answers

1

If I understand correctly, you will climb into Docker 2 containers, one with the bank and the other with your API using Nodejs + Express.

You can link them both using Docker-Compose. Here is an example of the Docker-Compose.yml file

version: "3.4"
volumes:
  data_sistema:
services:
  db_sistema:
    image: mysql:5.6
    ports:
      - "3306:3306"
    expose:
      - 3306
    volumes:
      - data_sistema:/var/lib/mysql
    environment:
      - MYSQL_ROOT_PASSWORD=123456
      - MYSQL_DATABASE=sistema
  app_sistema:
    build: ./
    image: app_sistema
    links:
      - db_sistema
    depends_on:
      - db_sistema
    environment:
      - DB_HOST=db_sistema
      - DB_USERNAME=root
      - DB_PASSWORD=123456
      - DB_DATABASE=sistema
      - DB_PORT=3306
      - WAIT_HOSTS=db_sistema:3306
    ports:
      - 3000:3000

Note that in this example I have two services, db_system which is the bank container and app_system which is the API container. In both, I have system variables (section Environment). Note that in app_system, I inform you that db_host is equal to the database service name within this Docker-Compose file.

In your database connection file (database.js) you can make the following change so that the file takes the data from the environment variables:

module.exports = {
  dialect: "mysql",
  host: process.env.DB_HOST,
  username: process.env.DB_USERNAME,
  password: process.env.DB_PASSWORD,
  database: process.env.DB_DATABASE,
  operatorAliases: false,
  define: {
    timestamps: true,
    underscored: true,
    underscoredAll: true
  }
};

The ideal is to leave this connection information in the file. env from the root of your project, and pull this data from there, rather than leaving it fixed in the connection file.

1


By described, the database is in Docker and the API is running on the local machine. However, the API is configured to connect to the database at the localhost address (IP 127.0.0.1 and port 3306).

Therefore, what was missing was the port of your container. To start a container and map a local port you need to add the parameter p at the helm run.

ex: docker run --name exemplo-mysql -d -p 3306:3306 -e MYSQL_ROOT_PASSWORD=my-secret-pw mysql

Browser other questions tagged

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