Search code examples
mongodbdockerdocker-composekeystonejs

How do I properly set up my Keystone.js app to run in docker with mongo?


I have built my app which runs fine locally. When I try to run it in docker (docker-compose up) it appears to start, but then throws an error message:

Creating mongodb ... done
Creating webcms  ... done
Attaching to mongodb, webcms

...

Mongoose connection "error" event fired with:
    MongoError: failed to connect to server [localhost:27017] on first connect

...

webcms exited with code 1

I have read that with Keystone.js you need to configure the Mongo location in the .env file, which I have:

MONGO_URI=mongodb://localhost:27017

Here is my Docker file:

# Use node 9.4.0
FROM node:9.4.0

# Copy source code
COPY . /app

# Change working directory
WORKDIR /app

# Install dependencies
RUN npm install

# Expose API port to the outside
EXPOSE 3000

# Launch application
CMD ["node","keystone"]

...and my docker-compose

version: "2"
services:
  # NodeJS app
  web:
    container_name: webcms
    build: .
    ports:
    - 3000:3000
    depends_on:
    - mongo

  # MongoDB
  mongo:
    container_name: mongo
    image: mongo
    volumes:
      - ./data:/data/db/mongo
    ports:
      - 27017:27017

When I run docker ps it confirms that mongo is up and running in a container...

CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                      NAMES
f3e06e4a5cfe        mongo               "docker-entrypoint.s…"   2 hours ago         Up 2 hours          0.0.0.0:27017->27017/tcp   mongodb

I am either missing some config or I have it configured incorrectly. Could someone tell me what that is?

Any help would be appreciated.

Thanks!


Solution

  • It is not working properly because you are sending the wrong host. your container does not understand what is localhost:27017 since it's your computer address and not its container address.

    Important to understand that each service has it's own container with a different IP. The beauty of the docker-compose that you do not need to know your container address! enough to know your service name:

    version: "2"
    
    volumes:
      db-data:
        driver: local
    
    services:
      web:
        build: .
        ports:
          - 3000:3000
        depends_on:
          - mongo
        environment:
          - MONGO_URI=mongodb://mongo:27017
    
      mongo:
        image: mongo
        volumes:
          - "db-data:/data/db/mongo"
        ports:
          - 27017:27017
    

    just run docker-compose up and you are all-set