#How to connect docker mysql to NESTJS using typeORM

27 messages · Page 1 of 1 (latest)

lapis cradle
#

I'm trying to connect my docker to NestJS using typeORM

database.module.ts

import { Module } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { TypeOrmModule } from "@nestjs/typeorm";

@Module({
    imports:[
        TypeOrmModule.forRootAsync({
            useFactory:(configService:ConfigService)=>({
                type: 'mysql',
                host: configService.getOrThrow('MYSQL_HOST'),
                port: configService.getOrThrow('MYSQL_PORT'),
                database: configService.getOrThrow('MYSQL_DATABASE'),
                username: configService.getOrThrow('MYSQL_USERNAME'),
                password: configService.getOrThrow("MYSQL_PASSWORD"),
                autoLoadEntities:true, 
                synchronize: configService.getOrThrow("MYSQL_SYNCHORIZED"),
            }),
            inject:[ConfigService],
        }),
    ]
})
export class DatebaseModule{}

how can i configure my docker

MYSQL_HOST=mypassword
MYSQL_DATABASE=nestjs_typeorm
MYSQL_HOST=127.0.0.1
MYSQL_PORT=3306
MYSQL_USERNAME=root
MYSQL_PASSWORD=randomrootpassword
MYSQL_SYNCHORIZED=true
wraith arch
#

you can create a docker-compose.yml file

#

Here is an example of a configuration:

#
version: "3"

services:
  db:
    image: mysql:8.0
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: root
      MYSQL_DATABASE: nest
    ports:
      - "3306:3306"
lapis cradle
#

like , do i need to put my docker settings inside database.module.ts

wraith arch
#

Yes exactly, you need to use the same configuration(username, password,port,name database, etc) you have inside the docker-compose.yml file

lapis cradle
wraith arch
lapis cradle
#

docker-compose up

#

is this true

wraith arch
#

To see the container list click on Containers (see screenshot)

lapis cradle
#

actually i just created it using that command

#

looks cool

#

i can run it now

#

and connect to it from my database.module.ts

#

lemme try

#

i think i have two ports

lapis cradle
velvet ibex
# lapis cradle i think i have two ports

The first portt is the local machine's port to bind to. Thesecond port is the container's port to expose. MySQL runs on the container port 3306, you bind it to your local 3306. If you did 33306:3306 then you would bind to local port 33306 instead. Useful tip for when you run multiple ofthe same service 😉

lapis cradle
#

so
type: 'mysql',
host: idk
port: 3306
database: idk
username: nest
password: root
autoLoadEntities:true,
synchronize:

wraith arch