Jan Kraus
Jan Kraus

Reputation: 25

Docker is not able to translate service name to IP address internally

I am trying to containerize three images: my Next.js application, Strapi image and Mongo database.

I have a Dockerfile with instructions for my Next.js application:

FROM node:14.15.0

WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
RUN npm run build
CMD [ "npm", "start" ]

And I am assembling all images in my docker-compose.yml:

version: "3.7"

services:

  mongo:
    container_name: example-mongo
    image: mongo:latest
    env_file: .env
    environment:
      MONGO_INITDB_DATABASE: ${DATABASE_NAME}
    volumes:
      - ./data:/data/db
    ports:
      - '27017:27017'

  strapi:
    container_name: example-strapi
    image: strapi/strapi:latest
    env_file: .env
    volumes:
      - ./strapi-app:/usr/src/strapi-app
    ports:
      - '1337:1337'
  
  app:
    container_name: example-app
    build:
      context: .
      dockerfile: Dockerfile
    depends_on:
      - mongo
      - strapi
    env_file:
      - .env
    volumes:
      - .:/usr/src/app
    ports:
      - '3000:3000'

volumes:
  data:
  strapi-app:

My .env file looks like this:

DATABASE_CLIENT=mongo
DATABASE_HOST=mongo
DATABASE_PORT=27017
DATABASE_NAME=example

The issue is, that when my Next.js application is running the npm run build, it fails when trying to connect to the Mongo Database (connection string that it fails on: mongodb://mongo:27017/example). The error is MongooseServerSelectionError: getaddrinfo ENOTFOUND mongo.

From what I found around forums and in some threads, this usually points to some Docker internal DNS issues. It is not able to translate mongo to the IP address of the Mongo DB service.

I tried running just the strapi image with the Mongo DB, at it is able to connect to the Mongo DB without a hiccup. Am I missing some config for my Next.js application? Here is a bare bones example, that replicates the issue, for anyone interested: https://gitlab.com/jan.kraus.cf/next-mongo-strapi

Upvotes: 2

Views: 429

Answers (1)

larsks
larsks

Reputation: 312530

You're getting that error during the build stage of your environment. This runs before any containers have started, so of course the mongo service isn't available.

You can reproduce this by simply running docker build . in the directory containing your Dockerfile. It gets as far as:

Step 7/8 : RUN npm run build
 ---> Running in 28aa6347395f

> learn-starter@0.1.0 build /usr/src/app
> next build

And fails soon after that with:

info  - Collecting page data...
Trying to connect to MongoDB on: mongodb://mongo:27017/example
MongooseServerSelectionError: getaddrinfo ENOTFOUND mongo
[...]

Your build can't have dependencies on external databases or other resources. Anything like that needs to happen at run time rather than build time.

Upvotes: 2

Related Questions