Can not connect MongoDB container from in the same container on AWS EC2

This is mongo docker-compose file;

  mongoDB:
    image: mongo
    command: mongod --port 10511
    environment:
      MONGO_INITDB_ROOT_USERNAME: kek
      MONGO_INITDB_ROOT_PASSWORD: 1234
      MONGO_INITDB_DATABASE: dbName
    ports:
      - "10511:10511"


  fastAPI:
    build: /backend
    ports:
      - "40050:80"
    environment:
      - DB_NAME=dbName
      - MONGO_URL=mongodb://kek:1234@mongoDB:10511/dbName?authSource=admin
    depends_on:
      - mongoDB

I created two container in AWS EC2. One for MongoDB and the other one is for Fast API.

I can connect MongoDB container from Fast API container because when sent POST method it accepts end returns 201, but I did not create GET method to see if it is created or not.

The problem is when connect to MongoDB container from the AWS EC2 with sudo docker exec -it <mongodb container> sh and try to connect mongo with my username and password that my Fast API container’s uses it, it throws “authorization failed” error.

Here is the Fast API connection string to MongoDB; mongodb://kek:1234@mongoDB:10511/dbName?authSource=admin

Here is the mongo connection string;mongosh --port 10511 -u kek -p 1234 --authenticationDatabase dbName

I can connect mongo with this; mongosh --port 10511 (in the MongoDB container), but I can’t do anything because of authorization issue.

I tried;

use dbName
db.auth('kek','1234')

and same, still authentication error.

I solved it.
I was creating my env. variable with " on AWS side.
So use ’

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.