502 response when conecting to an endpoint running on a docker container from another docker container

I have two different services ( A and B) A is calling an api endpoint of B. A and B are running in two different docker containers inside my localhost.
enter image description here

docker-compose.yml of A :

has ports 80:80 and expose 80

docker-compose.yml of B :
has ports 8881:8881 and expose 8881.

I can access http://localhost:8881/check from browser and getting 200 response
but not when calling from inside a function defined inside service A :

import requests
def check_service_B():
   url = "http://127.0.0.1:8881/check";
   resp = requests.get(url)
   print(resp.status_code)
   print(resp.content)

I am getting 502 response. I am stuck for the last 12 hours. Can anyone tell me how to fix this? I am happy to give more input if needed.

Source: Docker Questions