无法从linux主机连接到mongodb容器

时间:2015-03-21 17:18:50

标签: mongodb docker

我有以下仅安装mongodb 3的Dockerfile

# Start with docker's base ubuntu image
FROM ubuntu:14.04.2

# Mongodb prerequisite
RUN apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
RUN echo "deb http://repo.mongodb.org/apt/ubuntu "$(lsb_release -sc)"/mongodb-org/3.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.0.list

# Update package sources
RUN apt-get -y update

# Install Mongodb binaries
RUN apt-get -y install mongodb-org

# Copy configuratio file
COPY mongod.conf /etc/mongod.conf

# Create mongo data path (will be mapped to a volume on host machine later on)
RUN mkdir -p /data/db
RUN chown -R mongodb:mongodb /data/db

# Expose MongoDB port
EXPOSE 27017

# Run mongo with mongodb user
USER mongodb

# Run mongod using provided configuration file
ENTRYPOINT ["/usr/bin/mongod"]
CMD ["--config", "/etc/mongod.conf"]

我用

创建图像
sudo docker build -t mongod .

我用

运行容器
sudo docker run -d -P mongod

并确认它已经开始

> sudo docker ps
CONTAINER ID        IMAGE               COMMAND                CREATED             STATUS              PORTS                      NAMES
43c75e7e44b3        mongod:latest       "/usr/bin/mongod --c   3 minutes ago       Up 3 minutes        0.0.0.0:49165->27017/tcp   silly_mccarthy

当我从容器中运行mongo客户端时,它可以连接而没有任何错误:

> sudo docker exec -ti 43c75e7e44b3 bash

$ mongo

MongoDB shell version: 3.0.1
connecting to: test
Welcome to the MongoDB shell.
....

我的主机是Ubuntu 14.04盒子,网络接口/网桥是

docker0   Link encap:Ethernet  HWaddr 63:54:7b:f3:47:33
          inet addr:172.17.42.1  Bcast:0.0.0.0  Mask:255.255.0.0
          ....
em1       Link encap:Ethernet  HWaddr c4:2f:e3:64:ae:7c
          inet addr:192.168.1.101  Bcast:192.168.1.255  Mask:255.255.255.0
          ....
lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          ....

从我的主机,我无法连接到mongod容器

> mongo --port 49165

MongoDB shell version: 3.0.1
connecting to: 127.0.0.1:49165/test
2015-03-21T18:14:55.936+0100 I NETWORK  Socket recv() errno:104     Connection reset by peer 127.0.0.1:49165
2015-03-21T18:14:55.936+0100 I NETWORK  SocketException: remote:   127.0.0.1:49165 error: 9001 socket exception [RECV_ERROR] server [127.0.0.1:49165]
2015-03-21T18:14:55.936+0100 I NETWORK  DBClientCursor::init call() failed
2015-03-21T18:14:55.937+0100 E QUERY    Error: DBClientBase::findN: transport error: 127.0.0.1:49165 ns: admin.$cmd query: { whatsmyuri: 1 }
at connect (src/mongo/shell/mongo.js:181:14)
at (connect):1:6 at src/mongo/shell/mongo.js:181
exception: connect failed

这里有什么我想念的吗?

1 个答案:

答案 0 :(得分:1)

MongoDB的默认配置是将mongod绑定到localhost的IP。在mongod.conf中搜索以下行:

bindIp = 127.0.0.1

如果你使用像这样的哈希来评论这一行

# bindIp = 127.0.0.1

然后mongod将绑定到启动期间可用的所有 IP。如果您设置这样的特定IP

bindIp = 192.168.0.42

然后mongod仅绑定到此特定IP地址,并且只能在可以访问指定端口上的IP的主机上使用。