简体   繁体   中英

MYSQL:Connect to both localhost & host.docker.internal

I have to connect to both localhost as well as docker.

const db = new Sequelize({
  host : 'host.docker.internal'| process.env.DB_HOST,
  database: process.env.DB_NAME,
  username: process.env.DB_USER,
  password: process.env.DB_PASS,
  dialect: 'mysql'
})

In the following code, when I run node app.js it runs on the machine. But when I run docker run -p 3000:3000 [imagehash] it throws the following error

ConnectionRefusedError [SequelizeConnectionRefusedError]: connect ECONNREFUSED 127.0.0.1:3306

and when I run

const db = new Sequelize({
  host : 'host.docker.internal',
  database: process.env.DB_NAME,
  username: process.env.DB_USER,
  password: process.env.DB_PASS,
  dialect: 'mysql'
})

it runs perfectly on docker run -p 3000:3000 [imagehash]

How to run on both perfectly

NOTE: process.env.DB_HOST = localhost

When you construct the database connection information, check the environment variable first . It's often useful to set the fallback value to what you'd want this to be in your everyday development environment.

const db = new Sequelize({
  host: process.env.DB_HOST || 'localhost',
  ...
});

Then when you do run it in Docker, you need to provide the value of that environment variable.

# If the database isn't in a container
docker run -e DB_HOST=host.docker.internal -p 3000:3000 myapp
# If the database is in a container; typical Compose setup
version: '3.8'
services:
  app:
    build: .
    environment:
      - DB_HOST=db # matching the name of the service below
    ports:
      - 3000:3000
  db:
    image: mysql
    volumes:
      mysql_data: /var/lib/mysql/data
volumes:
  mysql_data:

I think you try to connect to a mysql db who run on the host, To make it work just add -.network host argument to your run command. related documentation

After that, the best pratice is to create a mysql db inside container and link it with your application

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM