我有简单的phpmyadmin
、mysql
容器。
我在nodejs
中创建了一个带有backend
的新文件夹。现在,我无法通过backend
连接到database
。
所有三个容器(phpmyadmin
,mysql
,api
)都工作并启动。但容器api不与数据库连接。
这是我用于连接的主db.js
文件,它总是抛出错误。
const mysql = require("mysql");
const db = mysql.createConnection({
host: "localhost",
user: "db_user",
password: "db_user_pass",
database: "any-game",
port: 8899,
});
db.connect((err) => {
if (err) {
throw new Error("Something went wrong!"); // Get error always in this line because can't connect to db
}
});
module.exports = db;
phpmyadmin
的网址是localhost:8899
。Phpmyadmin如我所期望的那样工作。没有任何错误。我可以通过docker-compose中的登录名和密码登录到数据库。但无法连接到后端。
和docker-compose.yml
文件
version: "3"
services:
phpmyadmin:
image: phpmyadmin/phpmyadmin
container_name: phpmyadmin1
environment:
- PMA_ARBITRARY=1
- PMA_HOST=db
- PMA_PORT=3306
restart: always
links:
- db
ports:
- 8899:80
depends_on:
- db
api:
build: ./api
container_name: api1
command: npm run start
restart: unless-stopped
ports:
- "3005:3005"
environment:
- PORT=3005
depends_on:
- phpmyadmin
db:
image: mysql
container_name: db
environment:
- MYSQL_ROOT_PASSWORD=my_secret_password
- MYSQL_DATABASE=guess-game
- MYSQL_USER=db_user
- MYSQL_PASSWORD=db_user_pass
restart: always
ports:
- 6033:3306
我试着这样写:
const db = mysql.createConnection({
host: "localhost",
user: "db_user",
password: "db_user_pass",
database: "any-game",
});
就像这样
const db = mysql.createConnection({
host: "localhost",
user: "db_user",
password: "db_user_pass",
database: "any-game",
port: 80,
});
或者
const db = mysql.createConnection({
host: "localhost",
user: "db_user",
password: "db_user_pass",
database: "any-game",
port: 6033, // DB port
});
偶数
const db = mysql.createConnection({
host: "127.0.0.1",
user: "db_user",
password: "db_user_pass",
database: "any-game",
});
请帮帮忙🙄
1条答案
按热度按时间unhi4e5o1#
在使用Docker容器时,要与不同容器进行通信,可以通过以下方式进行
1.使用主机名建立连接
1.使用代理和sidecar建立连接以利用localhost。
在您情况下,请尝试以下代码段: