'ValueError: Port must be an integer between 0 and 65535: 27017

Starting MongoDB with this connection string mongodb://mongo-service:27017 is giving me this error.

The issue only happens for me when running on Kubernetes. Localhost is working fine.

ERROR:src.app:Exception on /api/polls [GET]
Traceback (most recent call last):
  File "/.venv/lib/python3.10/site-packages/flask/app.py", line 2077, in wsgi_app
    response = self.full_dispatch_request()
  File "/.venv/lib/python3.10/site-packages/flask/app.py", line 1525, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/.venv/lib/python3.10/site-packages/flask/app.py", line 1523, in full_dispatch_request
    rv = self.dispatch_request()
  File "/.venv/lib/python3.10/site-packages/flask/app.py", line 1509, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
  File "/home/appuser/src/app.py", line 28, in get_all
    polls = list(repository.get_all_polls())
  File "/home/appuser/src/repository.py", line 11, in get_all_polls
    return _get_collection().find()
  File "/home/appuser/src/repository.py", line 28, in _get_collection
    return mongo.get_collection(DATABASE, COLLECTION)
  File "/home/appuser/src/mongo.py", line 15, in get_collection
    return MongoClient(connection_string).get_database(database).get_collection(collection)
  File "/.venv/lib/python3.10/site-packages/pymongo/mongo_client.py", line 704, in __init__
    res = uri_parser.parse_uri(
  File "/.venv/lib/python3.10/site-packages/pymongo/uri_parser.py", line 568, in parse_uri
    nodes = split_hosts(hosts, default_port=default_port)
  File "/.venv/lib/python3.10/site-packages/pymongo/uri_parser.py", line 376, in split_hosts
    nodes.append(parse_host(entity, port))
  File "/.venv/lib/python3.10/site-packages/pymongo/uri_parser.py", line 137, in parse_host
    raise ValueError("Port must be an integer between 0 and 65535: %s" % (port,))
ValueError: Port must be an integer between 0 and 65535: 27017

I couldn't find the reason in the docs.



Solution 1:[1]

As it is required by the Kubernetes manifest schema, Secret values must be encoded in Base 64, which I was doing like this:

$ echo 'mongodb://mongo-service:27017' | base64
bW9uZ29kYjovL21vbmdvLXNlcnZpY2U6MjcwMTcK

This was adding a line-break at the end, modifying the original string content, and breaking pymongo interpretation of the connection string. Tricky.

mongodb://mongo-service:27017

In my case the solution was to change to printf as pointed out in this answer:

$ printf mongodb://mongo-service:27017 | base64
bW9uZ29kYjovL21vbmdvLXNlcnZpY2U6MjcwMTc=

A new PR937 was created proposing a new message format which can outline this behavior.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1