Ameur Baccoucha
Ameur Baccoucha

Reputation: 699

How to run a nodejs app in a mongodb docker image?

i am getting this error when i try to run the commande "mongo" in the container bash:

Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed: SocketException: Error connecting to 127.0.0.1:27017 :: caused by :: Connection refused :connect@src/mongo/shell/mongo.js:328:13 @(connect):1:6exception: connect failed

i'm trying to set up a new nodejs app in a mongo docker image. the image is created fine with dockerfile in docker hub and i pull it, create a container and every thing is good but when i try to tape "mongo" commande in the bash a get the error. this is my dockerfile

FROM mongo:4
RUN apt-get -y update
RUN apt-get install -y nodejs npm
RUN apt-get install -y curl python-software-properties
RUN curl -sL https://deb.nodesource.com/setup_11.x | bash -
RUN apt-get install -y nodejs
RUN node -v
RUN npm --version
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
COPY . .
CMD [ "npm", "start"]
EXPOSE 3000

Upvotes: 0

Views: 2331

Answers (1)

David Maze
David Maze

Reputation: 159050

When your Dockerfile ends with CMD ["npm", "start"], it is building an image that runs your application instead of running the database.

Running two things in one container is slightly tricky and usually isn't considered a best practice. (You change your application code so you build a new image and delete and recreate your existing container; do you actually want to stop and delete your database at the same time?) You should run this as two separate containers, one running the standard mongo image and a second one based on a Dockerfile similar to this but FROM node. You might look into Docker Compose as a simple orchestration tool that can manage both containers together.

The one other thing that's missing in your example is any configuration that tells the application where its database is. In Docker this is almost never localhost ("this container", not "this physical host somewhere"). You should add a control to pass that host name in as an environment variable. In Docker Compose you'd set it to the name of the services: block running the database.

version: '3'
services:
  mongodb:
    image: mongodb:4
    volumes:
      - './mongodb:/data/db'
  app:
    build: .
    ports: '3000:3000'
    env:
      MONGODB_HOST: mongodb

(https://hub.docker.com/_/mongo is worth reading in detail.)

Upvotes: 3

Related Questions