gpt4 book ai didi

mysql - 设置 Docker MySql 数据库并将其连接到 BE

转载 作者:行者123 更新时间:2023-12-03 22:29:58 24 4
gpt4 key购买 nike

安装 Docker,下载 mysql 镜像,使用 VS Code。
这是我的 docker.compose.yml 文件:

version: '3'
services:
db:
image: mysql:latest
environment:
MYSQL_DATABASE: 'db'
# So you don't have to use root, but you can if you like
MYSQL_USER: 'root'
# You can use whatever password you like
MYSQL_PASSWORD: 'root'
# Password for root access
MYSQL_ROOT_PASSWORD: 'root'
ports:
# <Port exposed> : < MySQL Port running inside container>
- '3306:3306'
#security_opt:
#- seccomp:unconfined
cap_add:
- SYS_NICE # CAP_SYS_NICE
expose:
# Opens port 3306 on the container
- '3306'
# Where our data will be persisted
volumes:
# this creates paths on the container
- my-db:/var/lib/mysql
- my-db:/docker-entrypoint-initdb.d
# Names our volume
volumes:
my-db:
使用命令“docker compose up”,我看到并输出,我看到图像正在运行。我得到这个输出:
  • 容器 irp-backend_db_1 创建 0.0s
    附加到 db_1
    db_1 | 2021-06-10 13:23:30+00:00 [Note] [Entrypoint]: MySQL 服务器 8.0.25-1debian10 的入口点脚本已启动。
    db_1 | 2021-06-10 13:23:30+00:00 [注意] [入口点]:切换到专用用户 'mysql'
    db_1 | 2021-06-10 13:23:30+00:00 [Note] [Entrypoint]: MySQL 服务器 8.0.25-1debian10 的入口点脚本已启动。
    db_1 | 2021-06-10T13:23:30.769957Z 0 [系统] [MY-010116] [服务器]/usr/sbin/mysqld (mysqld 8.0.25) 从进程 1 开始
    db_1 | 2021-06-10T13:23:30.791485Z 1 [系统] [MY-013576] [InnoDB] InnoDB 初始化已开始。
    db_1 | 2021-06-10T13:23:30.955342Z 1 [系统] [MY-013577] [InnoDB] InnoDB 初始化已结束。
    db_1 | 2021-06-10T13:23:31.047007Z 0 [系统] [MY-011323] [服务器] X 插件准备好连接。绑定(bind)地址:'::' 端口:33060,套接字:/var/run/mysqld/mysqlx.sock
    db_1 | 2021-06-10T13:23:31.153833Z 0 [警告] [MY-010068] [服务器] CA 证书 ca.pem 是自我
    签。
    db_1 | 2021-06-10T13:23:31.154004Z 0 [系统] [MY-013602] [服务器] channel mysql_main 配置为支持 TLS。此 channel 现在支持加密连接。
    db_1 | 2021-06-10T13:23:31.158189Z 0 [警告] [MY-011810] [服务器] --pid 文件的不安全配置:所有操作系统用户都可以访问路径中的位置“/var/run/mysqld”。考虑选择一个
    不同的目录。
    db_1 | 2021-06-10T13:23:31.175606Z 0 [系统] [MY-010931] [服务器]/usr/sbin/mysqld:准备连接。版本:'8.0.25' 套接字:'/var/run/mysqld/mysqld.sock' 端口:3306 MySQL 社区服务器 - GPL。

  • 这是我的 config/config.json 文件:
    {
    "development": {
    "username": "root",
    "password": "root",
    "database": "database_development",
    "host": "localhost",
    "dialect": "mysql"
    },
    "test": {
    "username": "root",
    "password": "root",
    "database": "database_test",
    "host": "localhost",
    "dialect": "mysql"
    },
    "production": {
    "username": "root",
    "password": "root",
    "database": "database_production",
    "host": "localhost",
    "dialect": "mysql"
    }
    }
    我的迁移/create-user.js
    module.exports = {
    up: async (queryInterface, Sequelize) => {
    await queryInterface.createTable('Users', {
    id: {
    allowNull: false,
    autoIncrement: true,
    primaryKey: true,
    type: Sequelize.INTEGER
    },
    email: {
    type: Sequelize.STRING,
    allowNull: false
    },
    password: {
    type: Sequelize.STRING,
    allowNull: false
    },
    firstName: {
    type: Sequelize.STRING
    },
    lasrName: {
    type: Sequelize.STRING
    },
    createdAt: {
    allowNull: false,
    type: Sequelize.DATE
    },
    updatedAt: {
    allowNull: false,
    type: Sequelize.DATE
    }
    });
    },
    down: async (queryInterface, Sequelize) => {
    await queryInterface.dropTable('Users');
    }
    };
    模型/index.js
    const fs = require('fs');
    const path = require('path');
    const Sequelize = require('sequelize');
    const basename = path.basename(__filename);
    const env = process.env.NODE_ENV || 'development';
    const config = require(__dirname + '/../config/config.json')[env];
    const db = {};

    let sequelize;
    if (config.use_env_variable) {
    sequelize = new Sequelize(process.env[config.use_env_variable], config);
    } else {
    sequelize = new Sequelize(config.database, config.username, config.password, config);
    }

    // go through all files and do sequelize
    fs
    .readdirSync(__dirname)
    .filter(file => {
    return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
    })
    .forEach(file => {
    const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes);
    db[model.name] = model;
    });

    Object.keys(db).forEach(modelName => {
    if (db[modelName].associate) {
    db[modelName].associate(db);
    }
    });

    db.sequelize = sequelize;
    db.Sequelize = Sequelize;

    module.exports = db;
    这是我的模型/User.js
    const { Model } = require('sequelize');
    module.exports = (sequelize, DataTypes) => {
    class User extends Model {
    /**
    * Helper method for defining associations.
    * This method is not a part of Sequelize lifecycle.
    * The `models/index` file will call this method automatically.
    */
    static associate(models) {
    // define association here
    }
    };
    User.init({
    email: DataTypes.STRING,
    password: DataTypes.STRING,
    firstName: DataTypes.STRING,
    lasrName: DataTypes.STRING
    }, {
    sequelize,
    modelName: 'User',
    });
    return User;
    };
    为了获得更易读的代码,我有一个路由器
    路线/index.js
    const express = require("express");
    const router = express.Router();

    /**
    * router files
    */

    const userRoutes = require("./user/index");
    const clientRoutes = require("./client/index");

    /**
    * using route files
    */

    router.use("/users", userRoutes);

    router.get("/", (req, res) => {
    res.json({
    message: "🚀",
    });
    });

    module.exports = router;
    和我的用户 routes/user/index.js
    const { Router } = require("express");
    const router = Router();

    const userController = require("../../controllers/UserController");

    // get requests
    router.get("/", userController.getUsers);
    router.get("/getUserByEmail/:email", userController.getUserByEmail);

    // post requests
    router.post("/register", userController.register);
    router.post("/login", userController.login);
    router.post("/setUserPassword", userController.setUserPassword);

    module.exports = router;
    我的 package.json
    {
    "name": "nodejs-express-sequelize-mysql",
    "version": "1.0.0",
    "description": "Node.js Rest Apis with Express, Sequelize & MySQL",
    "main": "server.js",
    "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
    },
    "keywords": [
    "nodejs",
    "express",
    "rest",
    "api",
    "sequelize",
    "mysql"
    ],
    "author": "bezkoder",
    "license": "ISC",
    "dependencies": {
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "mysql2": "^2.0.2",
    "sequelize": "^5.21.2"
    }
    }
    我的 sequlize.js 文件
    import Sequelize from 'sequelize'
    import UserModel from "./models/User"

    TAG = "sequelize"

    // fields in the config.json file
    const sequelizeSqlite = new Sequelize("database", "username", "password", {
    dialect: 'sqlite',
    storage: "data/db/storage.sqlite"
    })

    const UserSqlite = UserModel(sequelizeSqlite, Sequelize);

    sequelizeSqlite.sync()
    .then(() => {
    console.log(TAG, "User db and user table have been created with Sqlite");
    })

    module.exports(UserSqlite);
    和最后一个文件
    server.js 文件:
    app.use(express.urlencoded({extended: true }));
    const db = require("./models");
    db.sequelize.sync();

    // simple route
    app.get("/", (req, res) => {
    res.json({ message: "Welcome to The Backend." });
    });

    app.use("./api", routes);

    // set port, listen for requests
    const PORT = process.env.PORT || 3000;

    app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}.`);
    });
  • 我运行: docker compose up ... 图像正在运行,我可以在 Docker for Windows
  • 上看到它
  • 我运行 node server.js ...它在图像上创建了一个表,我可以在 docker 扩展
  • 上看到它
  • 我无法使用 npm start
  • 运行项目

    我收到以下错误:
      nodejs-express-sequelize-mysql@1.0.0 start C:\Users\Win-10\Desktop\IRP\irp-backend
    > node server.js

    events.js:353
    throw er; // Unhandled 'error' event
    ^

    Error: listen EADDRINUSE: address already in use :::3000
    at Server.setupListenHandle [as _listen2] (net.js:1318:16)
    at listenInCluster (net.js:1366:12)
    at Server.listen (net.js:1452:7)
    at Function.listen (C:\Users\Win-10\Desktop\IRP\irp- backend\node_modules\express\lib\application.js:618:24)
    at Object.<anonymous> (C:\Users\Win-10\Desktop\IRP\irp-backend\server.js:32:5)
    at Module._compile (internal/modules/cjs/loader.js:1068:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1097:10)
    at Module.load (internal/modules/cjs/loader.js:933:32)
    at Function.Module._load (internal/modules/cjs/loader.js:774:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
    at internal/main/run_main_module.js:17:47
    Emitted 'error' event on Server instance at:
    at emitErrorNT (net.js:1345:8)
    at processTicksAndRejections (internal/process/task_queues.js:82:21) {
    code: 'EADDRINUSE',
    errno: -4091,
    syscall: 'listen',
    address: '::',
    port: 3000
    }
    我可以看到后端在浏览器 localhost:3000 中工作
    显示一行的白页: {"message":"Welcome to The Backend."}//my msg from server.js
    我仍然缺少一些东西,但我无法弄清楚。你能帮我么。

    最佳答案

    这个错误行Error: listen EADDRINUSE: address already in use :::3000localhost:3000 response ,
    建议 server.js 在 PORT:3000 启动并运行。
    npm start 与运行 node server.js 相同(我在脚本的 package.json 中没有看到它,但我猜它就在那里)。
    所以...尝试其中一种。这就像尝试使用 2 个不同的脚本访问同一个端口。
    我希望我做对了。
    实际上,
    为什么你在 2 个地方声明新的 Sequelize(...) 实例。
    还有为什么你的配置有 sqlite 而不是 mysql2?
    也许我误解了

    关于mysql - 设置 Docker MySql 数据库并将其连接到 BE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67922522/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com