Need help with Mongo config
mhariri2
PROOP

3 months ago

Hi,

I am stuck for about a week trying to make Mongodb access from my server. I have tried setting the mongo_url on the web server but still no luck. Here are my details:

My dockerfile

# Multi-stage build for Smart Quantitative Trading Platform
FROM python:3.11-slim

RUN apt-get update && apt-get install -y ca-certificates && \
    update-ca-certificates && \
    rm -rf /var/lib/apt/lists/*

WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .

ENV SSL_CERT_FILE=/etc/ssl/certs/ca-certificates.crt
# Run the application
CMD ["uvicorn", "server:app", "--host", "0.0.0.0", "--port", "8000"]

Variable Mongo_URL is set to (password obfuscated):
mongodb://mongo:*****@mongodb.railway.internal:27017

Mongo Client Code

def get_mongodb_client():
    uri = os.getenv("MONGO_URL")
    if not uri:
        raise ValueError("MONGO_URL environment variable is not set")

    client = MongoClient(uri, tls=False)
    client.admin.command("ping")

    print("Mongo OK")

    return client
Solved$10 Bounty

13 Replies

3 months ago

This thread has been marked as public for community involvement, as it does not contain any sensitive or personal information. Any further activity in this thread will be visible to everyone.

Status changed to Open itsrems 3 months ago


fra
HOBBYTop 10% Contributor

3 months ago

what error do you get?


dardameiz
PRO

3 months ago

you could try to add this:

mongodb://mongo:*****@mongodb.railway.internal:27017/?directConnection=true

because Railway’s internal networking requires directConnection=true for single MongoDB instances


mhariri2
PROOP

3 months ago

Did that and hardcoded the uri

I have been posting this issue over a week and I am almost ready to move to another hosting service. To make a long story short, I ended up using a railway hosted mongo db. I had the mongo_url set on the application server. I have also hardcoded the railway mongo url. My app runs locally and connects to mongo atlas so it works fine.

I am getting the error below when I push my code to railway. I am at my Witt’s end. Anybody has any ideas?

MongoDB connection failed: ServerSelectionTimeoutError: mongodb.railway.internal:27017: [Errno -2] Name or service not known (configured timeouts: socketTimeoutMS: 10000.0ms, connectTimeoutMS: 10000.0ms), Timeout: 10.0s, Topology Description: <TopologyDescription id: 69432fa40f15139764a09764, topology_type: Single, servers: [<ServerDescription ('mongodb.railway.internal', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('mongodb.railway.internal:27017: [Errno -2] Name or service not known (configured timeouts: socketTimeoutMS: 10000.0ms, connectTimeoutMS: 10000.0ms)')>]>


dardameiz
PRO

3 months ago

use the public URL temporarily to confirm it’s a networking issue. Go to MongoDB service, Settings, Networking, Enable public networking and use that URL instead to test?


mhariri2
PROOP

3 months ago

Done that. Does not work


mhariri2

Done that. Does not work

mhariri2
PROOP

3 months ago

Also, is railway support always this ineffective?


dardameiz
PRO

3 months ago

hmmm. interesting. not sure about railway’s support had not had any bigger issues yet.

I found this:

Search your code for any MongoClient() or get_mongodb_client() calls that run outside of a function - those are the problem. The internal hostname only resolves when the app is actually running and handling requests, not during startup.​​​​​​​​​​​​​​​​

Example:

# connects immediately at startup - FAILS because internal DNS not available yet

client = get_mongodb_client()

db = client["mydb"]

possible fix:

_client = None

def get_mongodb_client():

global _client

if _client is not None:

return _client

uri = os.getenv("MONGO_URL")

if not uri:

raise ValueError("MONGO_URL environment variable is not set")

_client = MongoClient(uri, tls=False)

_client.admin.command("ping")

print("Mongo OK")

return _client

def get_db():

return get_mongodb_client()["mydb"]

# Then in routes - only connects when request comes in:

@app.get("/whatever")

def some_endpoint():

db = get_db()

return db.users.find_one()


mhariri2
PROOP

3 months ago

Thank you for the response. The key here is that I run the code on my machine with mongo atlas connection and it works fine. The only thing I change is the connection string to railway Mongo and push it to railway and then the connection fail. The only difference is the mongo db url.

Thats why I am not sure why my code from my container can not see the Mongo on the railway mongo.

That is why I am bringing up railways support as being useless. I am not sure how to troubleshoot this on their side.


dardameiz
PRO

3 months ago

yeah sounds like a railway network issue if it works with Atlas. hope they will answer your. Keep it up!


fra
HOBBYTop 10% Contributor

3 months ago

can you try connecting via SSH to the container and try to connect to the db with the cli?


fra

can you try connecting via SSH to the container and try to connect to the db with the cli?

mhariri2
PROOP

3 months ago

Hi,

Thank you for the response. I have disabled TLS in the connection string and still getting the same error. Also, I am too dim to figure out how to SSH connect to my container. Documents I can not find.


fra
HOBBYTop 10% Contributor

3 months ago

To connect via SSH you can just left click on the service, and copy the ssh connection string

Also looking at old threads:


thesobercoder
PRO

3 months ago

I think you should add an exponential backoff strategy for connecting to the Mongo service. High chance your service tries to connect to it before even the Mongo service is ready.


Status changed to Solved itsrems 3 months ago


Loading...