如何将NodeJS Docker容器连接到mongoDB [英] How to connect nodeJS docker container to mongoDB

查看:312
本文介绍了如何将NodeJS Docker容器连接到mongoDB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在将作为docker容器运行的nodeJS应用程序连接到mongoDB时遇到问题.让我解释一下到目前为止我做了什么:

I have problems to connect a nodeJS application which is running as a docker container to a mongoDB. Let me explain what I have done so far:

$ docker ps

CONTAINER ID    IMAGE        COMMAND                  CREATED        STATUS        PORTS        NAMES
3a3732cc1d90    mongo:3.4    "docker-entrypoint..."   3 weeks ago    Up 3 weeks    27017/tcp    mongo_live

如您所见,已经有一个mongo docker容器正在运行.

As you can see, there is already a mongo docker container running.

现在,我正在运行我的nodeJS应用程序docker容器(它是由meteorJS构建的):

Now I'm running my nodeJS application docker container (which is a build from meteorJS):

$ docker run -it 0b422defbd59 /bin/bash

在这个Docker容器中,我想通过运行以下命令来运行应用程序:

In this docker container I want to run the application by running:

$ node main.js

现在我得到了错误

Error: MONGO_URL must be set in environment

我已经尝试通过设置以下内容来设置MONGO_URL:

I already tried to set MONGO_URL by setting:

ENV MONGO_URL mongodb://mongo_live:27017/

但这不起作用:

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

所以我的问题是如何连接到数据库,据我所知,它是正在运行的容器的外部".或者,如何为该容器设置一个新的数据库?

So my question is how to connect to a DB, which is - as far as I understand - 'outside' of the running container. Alternativly how do I set up a new DB to this container?

推荐答案

有几种方法可以做到这一点.

There are couple of ways to do it.

  • 在与mongodb相同的网络中运行您的应用程序:

  • run your app in the same network as your mongodb:

docker run --net container:mongo_live your_app_docker_image

# then you can use mongodb in your localhost
$ ENV MONGO_URL mongodb://localhost:27017/

  • 还可以链接两个容器:

  • Also you can link two containers:

    docker run --link mongo_live:mongo_live you_app_image ..
    # Now mongodb is accessible via mongo_live
    

  • 使用mongodb容器ip地址:

  • use mongodb container ip address:

    docker inspect -f '{{.NetworkSettings.IPAddress}}' mongo_live
    # you will get you container ip here
    
    $ docker run -it 0b422defbd59 /bin/bash
    # ENV MONGO_URL mongodb://[ip from previous command]:27017/
    

  • 您可以将mongodb端口绑定到主机,并在应用程序中使用主机的主机名

  • You can bind your mongodb port to your host and use host's hostname in your app

    您可以使用docker network并在同一网络中运行这两个应用程序

    You can use docker network and run both apps in the same network

    您可以将--add-host mongo_live:<ip of mongo container>传递给应用程序的docker run,然后将mongo_live用作mongodb url

    You could pass --add-host mongo_live:<ip of mongo container> to docker run for your application and then use mongo_live for mongodb url

    您还可以使用 docker compose 使您的生活更轻松;)

    You can also use docker compose to make your life easier ;)

    ...

    这篇关于如何将NodeJS Docker容器连接到mongoDB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆