Home > Back-end >  Error: getaddrinfo ENOTFOUND trying to connect to mongo from container
Error: getaddrinfo ENOTFOUND trying to connect to mongo from container

Time:11-21

I created an API using node.js

I converted it to an image by running the command docker build -t droneapi:1.0 using this Dockerfile.

FROM node:19-alpine

ENV MONGO_DB_USERNAME = admin \
    MONGO_DB_PWD=password

RUN mkdir -p /home/droneAPI

COPY . /Users/styles/Programming/DroneAPI2

CMD ["node", "/Users/styles/Programming/DroneAPI2/Drones/server.js"]

I ran docker run droneapi:1.0 to create a container to talk to my mongodb container but I received the error: getaddrinfo ENOTFOUND mongodb

I’m using mongoose to try and communicate with the db

onst connectDB = async () => {
    try{
        const conn = await mongoose.connect("mongodb://admin:password@mongodb:27017", {dbName: 'drobedb'})
        console.log(`MongoDB Connected: ${conn.connection.host}`.cyan.underline)

    }catch (error){
       console.log(`Error: ${error.message}`.red.underline.bold)
       process.exit(1)
    }
}

I have tried to replace the 'mongodb' in the connection string with localhost and I receive Error: connect ECONNREFUSED 127.0.0.1:27017

Here is my mongo.yaml file

version: '3'
services:
    mongodb:
        image: mongo
        ports:
            - 27017:27017
        environment:
            - MONGO_INITDB_ROOT_USERNAME=admin
            - MONGO_INITDB_ROOT_PASSWORD=password
    mongo-express:
        image: mongo-express
        ports:
            - 8081:8081
        environment:
            - ME_CONFIG_MONGODB_ADMINUSERNAME=admin
            - ME_CONFIG_MONGODB_ADMINPASSWORD=password
            - ME_CONFIG_MONGODB_SERVER=mongodb

I'm new to docker so please any assistance will be appreciated

CodePudding user response:

When we start a container stack through a compose-file, a network for this compose stack is created for us, and all containers are attached to this network. When we start a container through docker run ..., it is attached to the default network. Containers in different networks cannot communicate with each other. My recommendation would be to add the dronapi-container to the compose file:

version: '3'
services:
  ...
  drone-api:
    bulid:
      context: .
      dockerfile: path/to/Dockerfile
    ...
    depends_on:
      - mongodb # to start this container after mongodb has been started    

If we want to start the stack, we can run docker compose up -d. Notice that if the image was built before, it will not be automatically rebuilt. To rebuild the image, we can run docker compose up --build -d.


As an aside: I would recommend following the 12 factors for cloud-native applications (12factors.net). In particular, I would recommend to externalize the database configuration (12factors.net).

  • Related