인프런 커뮤니티 질문&답변

진승이님의 프로필 이미지
진승이

작성한 질문수

Slack 클론 코딩[백엔드 with NestJS + TypeORM]

MySQL이 연결되지않습니다

해결된 질문

작성

·

598

·

수정됨

0

Error: connect ECONNREFUSED ::1:3306

at TCPConnectWrap.afterConnect [as oncomplete] 라는 오류가 뜹니다

상황설명 : create~~ 가 뜨면서 sleact DB가 만들어졌다가 3306이 이미 써져있어서 그렇다라는 글을 보고 sudo killall mysqld 를 썼다가 DB가 다 날라가고 나서 다시 MySQL을 깔고 db:create, start:dev를 하였더니 똑같이 저런 오류가 뜹니다..

import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { LoggerMiddleware } from './middlewares/logger.middlware';
import { UsersModule } from './users/users.module';
import { WorkspacesModule } from './workspaces/workspaces.module';
import { ChannelsModule } from './channels/channels.module';
import { DmsModule } from './dms/dms.module';
import { UsersService } from './users/users.service';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Users } from './entities/Users';
import { WorkspaceMembers } from './entities/WorkspaceMembers';
import { ChannelChats } from './entities/ChannelChats';
import { ChannelMembers } from './entities/ChannelMembers';
import { Channels } from './entities/Channels';
import { DMs } from './entities/DMs';
import { Mentions } from './entities/Mentions';
import { Workspaces } from './entities/Workspaces';

@Module({
  imports: [
    ConfigModule.forRoot({ isGlobal: true }),
    UsersModule,
    WorkspacesModule,
    ChannelsModule,
    DmsModule,
    TypeOrmModule.forRoot({
      type: 'mysql',
      host: 'localhost',
      port: 3306,
      username: process.env.DB_USERNAME,
      password: process.env.DB_PASSWORD,
      database: process.env.DB_DATABASE,
      entities: [
        ChannelChats,
        ChannelMembers,
        Channels,
        DMs,
        Mentions,
        Users,
        WorkspaceMembers,
        Workspaces,
      ],
      synchronize: true,
      logging: true,
      keepConnectionAlive: true,
      charset: 'utf8mb4_general_ci',
    }),
    TypeOrmModule.forFeature([Users]),
  ],
  controllers: [AppController],
  providers: [AppService, ConfigService, UsersService],
})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(LoggerMiddleware).forRoutes('*');
  }
}

 

DB_USERNAME=root
DB_PASSWORD=저의 비밀번호입력했습니다
DB_DATABASE=sleact
PORT=3000

답변 1

0

제로초(조현영)님의 프로필 이미지
제로초(조현영)
지식공유자

mysql을 안 켜셔서 그렇습니다. sudo service start같은걸로 실행하세요

진승이님의 프로필 이미지
진승이
질문자

image

[Nest] 13149  - 2023. 08. 23. 오후 11:24:04   ERROR [TypeOrmModule] Unable to connect to the database. Retrying (8)...
Error: connect ECONNREFUSED ::1:3306
    at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1494:16)
    --------------------
    at Protocol._enqueue (/Users/yujinseung/Desktop/slack_nest/node_modules/mysql/lib/protocol/Protocol.js:144:48)
    at Protocol.handshake (/Users/yujinseung/Desktop/slack_nest/node_modules/mysql/lib/protocol/Protocol.js:51:23)
    at PoolConnection.connect (/Users/yujinseung/Desktop/slack_nest/node_modules/mysql/lib/Connection.js:116:18)
    at Pool.getConnection (/Users/yujinseung/Desktop/slack_nest/node_modules/mysql/lib/Pool.js:48:16)
    at /Users/yujinseung/Desktop/slack_nest/src/driver/mysql/MysqlDriver.ts:1268:18
    at new Promise (<anonymous>)
    at MysqlDriver.createPool (/Users/yujinseung/Desktop/slack_nest/src/driver/mysql/MysqlDriver.ts:1265:16)
    at MysqlDriver.connect (/Users/yujinseung/Desktop/slack_nest/src/driver/mysql/MysqlDriver.ts:400:36)
    at DataSource.initialize (/Users/yujinseung/Desktop/slack_nest/src/data-source/DataSource.ts:249:27)
    at /Users/yujinseung/Desktop/slack_nest/node_modules/@nestjs/typeorm/dist/typeorm-core.module.js:171:34

image

실행을 시키고 db:create, start:dev를 해도 똑같이 위 에러가 뜹니다..

그 혹시 .env파일이 잘못된건가 싶은데 .env파일 보여주실수있나용..

 

제로초(조현영)님의 프로필 이미지
제로초(조현영)
지식공유자

저 mysql 서버의 포트를 3306으로 하신 거 맞나요? .env는 관련이 없습니다.

ipv4:3306에 mysql 실행하셨는데 ipv6:3306으로 연결하려고 하시는 것 같습니다.

제로초(조현영)님의 프로필 이미지
제로초(조현영)
지식공유자

host에 localhost 대신 127.0.0.1 해보세요.

https://kong-dev.tistory.com/126

진승이님의 프로필 이미지
진승이
질문자

- app.module.ts-

import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { LoggerMiddleware } from './middlewares/logger.middlware';
import { UsersModule } from './users/users.module';
import { WorkspacesModule } from './workspaces/workspaces.module';
import { ChannelsModule } from './channels/channels.module';
import { DmsModule } from './dms/dms.module';
import { UsersService } from './users/users.service';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Users } from './entities/Users';
import { WorkspaceMembers } from './entities/WorkspaceMembers';
import { ChannelChats } from './entities/ChannelChats';
import { ChannelMembers } from './entities/ChannelMembers';
import { Channels } from './entities/Channels';
import { DMs } from './entities/DMs';
import { Mentions } from './entities/Mentions';
import { Workspaces } from './entities/Workspaces';

@Module({
  imports: [
    ConfigModule.forRoot({ isGlobal: true }),
    UsersModule,
    WorkspacesModule,
    ChannelsModule,
    DmsModule,
    TypeOrmModule.forRoot({
      type: 'mysql',
      host: '127.0.0.1',
      port: 3306,
      username: process.env.DB_USERNAME,
      password: process.env.DB_PASSWORD,
      database: process.env.DB_DATABASE,
      entities: [
        ChannelChats,
        ChannelMembers,
        Channels,
        DMs,
        Mentions,
        Users,
        WorkspaceMembers,
        Workspaces,
      ],
      synchronize: false,
      logging: true,
      keepConnectionAlive: true,
      charset: 'utf8mb4_general_ci',
    }),
    TypeOrmModule.forFeature([Users]),
  ],
  controllers: [AppController],
  providers: [AppService, ConfigService, UsersService],
})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(LoggerMiddleware).forRoutes('*');
  }
}
- dataSource.ts

import { DataSource } from 'typeorm';
import dotenv from 'dotenv';
import { ChannelChats } from './src/entities/ChannelChats';
import { ChannelMembers } from './src/entities/ChannelMembers';
import { Channels } from './src/entities/Channels';
import { DMs } from './src/entities/DMs';
import { Mentions } from './src/entities/Mentions';
import { Users } from './src/entities/Users';
import { WorkspaceMembers } from './src/entities/WorkspaceMembers';
import { Workspaces } from './src/entities/Workspaces';

dotenv.config();

const dataSource = new DataSource({
  type: 'mysql',
  host: '127.0.0.1',
  port: 3306,
  username: process.env.DB_USERNAME,
  password: process.env.DB_PASSWORD,
  database: process.env.DB_DATABASE,
  entities: [
    ChannelChats,
    ChannelMembers,
    Channels,
    DMs,
    Mentions,
    Users,
    WorkspaceMembers,
    Workspaces,
  ],
  migrations: [__dirname + '/src/migrations/*.ts'],
  charset: 'utf8mb4_general_ci',
  synchronize: false,
  logging: true,
});

export default dataSource;

말씀하신대로 했는데 이제는 BaseError: Cannot find module 'src/entities/Channels' 라는 오류가 뜹니다 왜 그런지 모르겠습니다...ㅠㅠ

혹시나해서 깃허브 주소 올립니닷..! https://github.com/jinseung0327/slack-nestjs

제로초(조현영)님의 프로필 이미지
제로초(조현영)
지식공유자

에러메시지 자르지말고 전부 올려주세요. 어디서 에러가 났는지 알아야합니다

진승이님의 프로필 이미지
진승이
질문자

yujinseung@yujinseung-ui-MacBookPro slack_nest % npm run seed

> study_nest@0.0.1 seed
> ts-node ./node_modules/typeorm-extension/bin/cli.cjs seed:run -d ./dataSource.ts

ℹ DataSource Directory: /Users/yujinseung/Desktop/slack_nest                                                                                           오후 5:10:17
ℹ DataSource Name: dataSource.ts                                                                                                                       오후 5:10:17
query: SELECT VERSION() AS `version`
typeorm-extension seed:run

Populate the database with an initial data set or generated data by a factory.

옵션:
  -h, --help               도움말 표시                                  [불리언]
      --preserveFilePaths  This option indicates if file paths should be
                           preserved.                   [불리언] [기본값: false]
  -r, --root               Root directory of the project.
                                [기본값: "/Users/yujinseung/Desktop/slack_nest"]
      --tsconfig, --tc     Name (or relative path incl. name) of the tsconfig
                           file.                       [기본값: "tsconfig.json"]
  -d, --dataSource         Name (or relative path incl. name) of the data-source
                           file.                         [기본값: "data-source"]
  -n, --name               Name (or relative path incl. name) of the seeder.
  -v, --version            버전 표시                                    [불리언]

BaseError: Cannot find module 'src/entities/Channels'
Require stack:
- /Users/yujinseung/Desktop/slack_nest/src/database/seeds/create-initial-data.ts
- /Users/yujinseung/Desktop/slack_nest/node_modules/locter/dist/index.cjs
- /Users/yujinseung/Desktop/slack_nest/node_modules/typeorm-extension/dist/index.cjs
- /Users/yujinseung/Desktop/slack_nest/node_modules/typeorm-extension/bin/cli.cjs
    at ModuleLoader.loadSync (/Users/yujinseung/Desktop/slack_nest/node_modules/locter/src/loader/built-in/module/module.ts:179:23)
    at ModuleLoader.loadSync (/Users/yujinseung/Desktop/slack_nest/node_modules/locter/src/loader/built-in/module/module.ts:172:37)
    at ModuleLoader.execute (/Users/yujinseung/Desktop/slack_nest/node_modules/locter/src/loader/built-in/module/module.ts:55:31)
    at async prepareSeederSeeds (/Users/yujinseung/Desktop/slack_nest/node_modules/typeorm-extension/src/seeder/utils/prepare.ts:29:35)
    at async SeederExecutor.execute (/Users/yujinseung/Desktop/slack_nest/node_modules/typeorm-extension/src/seeder/executor.ts:42:32)
    at async Object.handler (/Users/yujinseung/Desktop/slack_nest/node_modules/typeorm-extension/bin/cli.cjs:264:9) {
  options: {
    code: 'MODULE_NOT_FOUND',
    message: "Cannot find module 'src/entities/Channels'\n" +
      'Require stack:\n' +
      '- /Users/yujinseung/Desktop/slack_nest/src/database/seeds/create-initial-data.ts\n' +
      '- /Users/yujinseung/Desktop/slack_nest/node_modules/locter/dist/index.cjs\n' +
      '- /Users/yujinseung/Desktop/slack_nest/node_modules/typeorm-extension/dist/index.cjs\n' +
      '- /Users/yujinseung/Desktop/slack_nest/node_modules/typeorm-extension/bin/cli.cjs',
    stack: "Error: Cannot find module 'src/entities/Channels'\n" +
      'Require stack:\n' +
      '- /Users/yujinseung/Desktop/slack_nest/src/database/seeds/create-initial-data.ts\n' +
      '- /Users/yujinseung/Desktop/slack_nest/node_modules/locter/dist/index.cjs\n' +
      '- /Users/yujinseung/Desktop/slack_nest/node_modules/typeorm-extension/dist/index.cjs\n' +
      '- /Users/yujinseung/Desktop/slack_nest/node_modules/typeorm-extension/bin/cli.cjs\n' +
      '    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:1077:15)\n' +
      '    at Function.Module._resolveFilename.sharedData.moduleResolveFilenameHook.installedValue [as _resolveFilename] (/Users/yujinseung/Desktop/slack_nest/node_modules/@cspotcode/source-map-support/source-map-support.js:811:30)\n' +
      '    at Function.Module._load (node:internal/modules/cjs/loader:922:27)\n' +
      '    at Module.require (node:internal/modules/cjs/loader:1143:19)\n' +
      '    at require (node:internal/modules/cjs/helpers:110:18)\n' +
      '    at Object.<anonymous> (/Users/yujinseung/Desktop/slack_nest/src/database/seeds/create-initial-data.ts:1:1)\n' +
      '    at Module._compile (node:internal/modules/cjs/loader:1256:14)\n' +
      '    at Module.m._compile (/Users/yujinseung/Desktop/slack_nest/node_modules/ts-node/src/index.ts:1618:23)\n' +
      '    at Module._extensions..js (node:internal/modules/cjs/loader:1310:10)\n' +
      '    at Object.require.extensions.<computed> [as .ts] (/Users/yujinseung/Desktop/slack_nest/node_modules/ts-node/src/index.ts:1621:12)'
  }
}

입니닷..!

진승이님의 프로필 이미지
진승이
질문자

아 그 https://www.inflearn.com/questions/955712/%EC%97%94%ED%8B%B0%ED%8B%B0-%EA%B2%BD%EB%A1%9C%EC%97%90-%EC%A0%88%EB%8C%80%EA%B2%BD%EB%A1%9C%EC%99%80-%EC%83%81%EB%8C%80%EA%B2%BD%EB%A1%9C-%EC%9D%98%ED%95%9C-%EB%AA%A8%EB%93%88-%EC%9D%B8%EC%8B%9D 이글을 보고 상대경로로 바꾸어서 해보았는데

> ts-node ./node_modules/typeorm-extension/bin/cli.cjs seed:run -d ./dataSource.ts

ℹ DataSource Directory: /Users/yujinseung/Desktop/slack_nest                                                                                           오후 5:14:24
ℹ DataSource Name: dataSource.ts                                                                                                                       오후 5:14:24
query: SELECT VERSION() AS `version`
query: INSERT INTO `workspaces`(`id`, `name`, `url`, `createdAt`, `updatedAt`, `deletedAt`, `OwnerId`) VALUES (?, ?, ?, DEFAULT, DEFAULT, DEFAULT, DEFAULT) -- PARAMETERS: [1,"Sleact","sleact"]
query: SELECT `Workspaces`.`id` AS `Workspaces_id`, `Workspaces`.`createdAt` AS `Workspaces_createdAt`, `Workspaces`.`updatedAt` AS `Workspaces_updatedAt`, `Workspaces`.`deletedAt` AS `Workspaces_deletedAt` FROM `workspaces` `Workspaces` WHERE ( `Workspaces`.`id` = ? ) AND ( `Workspaces`.`deletedAt` IS NULL ) -- PARAMETERS: [1]
query: INSERT INTO `channels`(`id`, `name`, `private`, `createdAt`, `updatedAt`, `WorkspaceId`) VALUES (?, ?, ?, DEFAULT, DEFAULT, ?) -- PARAMETERS: [1,"일반",false,1]
query: SELECT `Channels`.`id` AS `Channels_id`, `Channels`.`private` AS `Channels_private`, `Channels`.`createdAt` AS `Channels_createdAt`, `Channels`.`updatedAt` AS `Channels_updatedAt` FROM `channels` `Channels` WHERE `Channels`.`id` = ? -- PARAMETERS: [1]
yujinseung@yujinseung-ui-MacBookPro slack_nest % 

이렇게 되었습니다! 성공인가요?

제로초(조현영)님의 프로필 이미지
제로초(조현영)
지식공유자

네 성공입니다!!

진승이님의 프로필 이미지
진승이

작성한 질문수

질문하기