Problem with access to Mongodb on Amazon EC2

2020-05-18 03:58发布

问题:

i've got another question for you. I have Amazon EC2 instance with mondodb installed. It works great except one thing - i can't access (connect to) it from outside (my PC). I think the problem with Security Groups. It's some sort of default firewall. Does anyone know how to configure EC2 instance to have access to mongodb? Thanks in advance.

回答1:

You need to add a security group exception for the port 27017 if you are using default config for you to access it from outside. For security group configuration, please check the amazon EC2 documentation. And if you are using a different port on Mongo, change the security group port accordingly.

--Sai



回答2:

Think carefully before doing this. If you open the ports, make sure you restrict the IP numbers that can access it, otherwise anyone will be able to access your database. You can enable authentication in MongoDB, but it's not particularly safe, just a username and password. You should not have your database open to the internet, it is not a good idea.

A better way than opening up ports in the EC2 firewall is to open an SSH tunnel an forward the port, this makes sure that only you can access the database, and only while the SSH tunnel is active.

Open up a new terminal and run this command (replacing user and host with the user you use when SSH'ing to your server and the name of the server):

ssh user@host -N -L 27017:127.0.0.1:27017

The command will forward the port 27017 on your computer to the same port on the server. To connect to the MongoDB instance simply run mongo in a terminal (if that doesn't work, try mongo --host 127.0.0.1 or even mongo --host 127.0.0.1 --port 27017).

If you run MongoDB on your local machine you will have to change the first port, since the local server is already using it. In that case run this command instead:

ssh user@host -N -L 27018:127.0.0.1:27017

and then connect with

mongo --port 27018

(possibly adding --host 127.0.0.1 if it doesn't work).

When you're done working with the database, exit mongo and press ctrl-C in the terminal with the SSH command.



回答3:

Is your EC2 instance a Windows server by any chance? If so, in addition to EC2's Security Groups you also need to configure Windows Firewall to allow the incoming connection.

Go To Administrative Tools, Windows Firewall with Advanced Security, and configure a new Rule that allows incoming connections on port 27017 (the default mongo port) or whatever port you've chosen.