[英]MYSQL:Connect to both localhost & host.docker.internal
I have to connect to both localhost as well as docker.我必须同时连接到本地主机和 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.在下面的代码中,当我运行node app.js
时,它会在机器上运行。 But when I run docker run -p 3000:3000 [imagehash]
it throws the following error但是当我运行docker run -p 3000:3000 [imagehash]
它会抛出以下错误
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]
它在docker run -p 3000:3000 [imagehash]
上完美运行
How to run on both perfectly如何完美地同时运行
NOTE: process.env.DB_HOST = localhost注意: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.然后,当您在 Docker 中运行它时,您需要提供该环境变量的值。
# 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.我认为您尝试连接到在主机上运行的 mysql 数据库,要使其正常工作,只需将-.network host
参数添加到您的运行命令。 related documentation相关文件
After that, the best pratice is to create a mysql db inside container and link it with your application之后,最好的做法是在容器内创建一个 mysql 数据库并将其与您的应用程序链接
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.