简体   繁体   中英

Docker compose getting error ECONNREFUSED 127.0.0.1:27018 with MongoDB and NodeJs

I am trying to setup some containers for my NestJS + TypeORM + MongoDB environment by using Docker Compose in a Windows 11 host, but I am getting an ECONNREFUSED error:

nestjs-docker-api-1    | [Nest] 1  - 07/23/2022, 8:45:32 AM   ERROR [TypeOrmModule] Unable to connect to the database. Retrying (1)...
nestjs-docker-api-1    | MongoServerSelectionError: connect ECONNREFUSED 127.0.0.1:27018
nestjs-docker-api-1    |     at Timeout._onTimeout (/usr/src/app/node_modules/mongodb/lib/sdam/topology.js:293:38)
nestjs-docker-api-1    |     at listOnTimeout (internal/timers.js:554:17)
nestjs-docker-api-1    |     at processTimers (internal/timers.js:497:7)

I have created the following Dockerfile to configure the NestJS API container:

FROM node:12

# Create app directory
WORKDIR /usr/src/app

# A wildcard is used to ensure both package.json AND package-lock.json are copied
COPY package*.json ./

# Install app dependencies
RUN npm install 

# Bundle app source
COPY . .


EXPOSE 8080

# Creates a "dist" folder with the production build
RUN npm run build

# Start the server using the production build
CMD [ "node", "dist/main.js" ]

And then I reference this from Docker Compose with the following docker-compose.yml :

version: "3.9"
services:
    mongo:
        image: mongo
        ports:
            - "27018:27017"
        restart: always
        environment: 
              ME_CONFIG_MONGODB_ADMINUSERNAME: root
              ME_CONFIG_MONGODB_ADMINPASSWORD: example 
    api:
        image: image_name
        build: . 
        depends_on: 
            - mongo
        environment: 
            NODE_ENV: development
            PORT: 3000
            USERNAME : root,
            PASSWORD : example
        ports:
            - "8000:3000"

Finally, I set the TypeORM configuration to match with the Docker Compose file:

@Module({
  imports: [ TypeOrmModule.forRoot({
    type: 'mongodb',
    host: 'localhost',
    port: 27018,
    database: 'admin',
    entities: [],
    synchronize: true,
  })],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

I tried a lot but the code doesn't work.Any help?

from docs :

By default Compose sets up a single network for your app.

you have to use the name of service which is mongo here to connect to it through the network created by compose instead of localhost .

or if you want to connect to localhsot directly you can add network_mode: "host" to your docker-compose file.

more about network_mode here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM