Ankit Sahay
Ankit Sahay

Reputation: 2043

Confusion with port number in MongoDB used by client connections

When I start MongoDB using mongod.exe it displays a message like "waiting for connections on port 27017", but when I execute mongo.exe the log message is "connection accepted from 127.0.0.1:60501".

Now, when I use PyMongo to connect to the DB I assumed that the port number to be used is "60501" since this is the port where the connection was established. Surprisingly I got an error saying "connection refused". I thought there was some problem with my MongoDB installation, config file placement, etc.

When nothing fixed it, I just played around by changing the port number to 27017, and this actually fixed the problem. Can someone explain how this worked out?

Upvotes: 0

Views: 1314

Answers (1)

Stennie
Stennie

Reputation: 65323

This behaviour is not specific to MongoDB. As part of the TCP/IP client/server protocol, services listen on configured ports (typically with well known defaults like 27017 for mongod). Clients connect to a server port and also establish their own ephemeral/dynamic port to use for the duration of a client/server session.

Each active session from the same client IP will use a distinct port on the client. The ephemeral port is logged to identify different client connections as they are established.

The logging in your case might be slightly confusing since you are connecting from localhost (127.0.0.1) where the server is also running, but the correct port to connect to is the mongod server port (default: 27017).

Upvotes: 4

Related Questions