简体   繁体   English

使用docker连接nodejs和mongo

[英]Connection nodejs and mongo with docker

This is my docker-compose-file: 这是我的docker-compose-file:

version: "2"
services:
  rest-api:
    build: .
    ports:
      - "3007:3007"
    links:
      - mongo
  mongo:
    image: mongo
    volumes:
      - /data/mongodb/db:/data/db
    ports:
      - "27017:27017"

This is my Dockerfile: 这是我的Dockerfile:

FROM mhart/alpine-node:latest

RUN rm -rf /tmp/node_modules
ADD package.json /tmp/package.json
RUN cd /tmp && npm install
RUN mkdir -p /opt/app && cp -a /tmp/node_modules /opt/app/

WORKDIR /opt/app
ADD . /opt/app

EXPOSE 3007

CMD ["node", "index.js"]

When I run the image, node is not able to connect to mongo: 当我运行映像时,节点无法连接到mongo:

MongoError: failed to connect to server [localhost:27017] on first connect

What can be wrong? 有什么事吗 How can I debug this? 我该如何调试?

Update: 更新:

In my node app I have: 在我的节点应用程序中,我有:

let connection = mongoose.connect('mongodb://localhost/myapp');

Node is trying to connect to Mongo on localhost , which fails because it is not running in the same container as Node. Node正在尝试连接到localhost上的Mongo,该操作失败,因为它未与Node在同一容器中运行。 Instead, it runs in a different container, ie on a different host. 相反,它在另一个容器中运行,即在另一个主机上。

You probably have a line like this in your application: 您的应用程序中可能会有这样的一行:

var url = 'mongodb://localhost:27017/myproject';

It defines where the MongoDB is located. 它定义了MongoDB的位置。 You need to change localhost to the actual host, which in your case would be mongo . 您需要将localhost更改为实际的主机,在您的情况下为mongo

In your node app you need to reference your container instead of localhost. 在您的节点应用程序中,您需要引用您的容器而不是本地主机。

In your connection string to mongo use the name mongo as the host you are probably just using the default at the minute 在您与mongo的连接字符串中,使用名称mongo作为主机,您可能只是在此时使用默认值

https://docs.mongodb.com/manual/reference/connection-string/ https://docs.mongodb.com/manual/reference/connection-string/

eg 例如

mongodb://mongo:27017/

You need to do this because the mongo database is in a separate container (with a different IP address) they are linked via TCP so localhost relates to the container node is in. 您需要执行此操作,因为mongo数据库位于单独的容器中(具有不同的IP地址),它们通过TCP链接在一起,因此与容器节点相关的localhost在其中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM