将后端连接到 docker 中的数据库

Connect backend with database in docker

我有简单的 phpmyadminmysql 个容器。

我在 nodejs 中用 backend 创建了新文件夹。现在,我无法通过 backend.

连接到 database

所有三个容器(phpmyadminmysqlapi)都可以运行并启动。但是容器 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;

Url 对于 phpmyadminlocalhost: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",
});

请帮忙

在使用docker个容器时,要与不同的容器进行通信,可以通过以下方式进行

  1. 使用主机名建立连接
  2. 使用代理和 sidecar 建立连接以使用本地主机。

对于您的情况,请尝试以下代码段,

const db = mysql.createConnection({
    host: "db",
    user: "db_user",
    password: "db_user_pass",
    database: "any-game",
    port: 3306,
});