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