Docker Community Forums

Share and learn in the Docker community.

Connection refused while connecting two containers


I am trying to connect my crud app image with postgres database. But is is showing an error : connection refused. I have exposed port of both the containers. I am passing database params while running app image.

If you are

getting Connection refused while trying to communicate between two containers
trying to communicate between two containers from different docker-compose projects and don’t want to use the same network (because let’s say they would have PostgreSQL or Redis container on the same port and you would prefer to not changing these ports and not use it at the same network)
developing locally and want to imitate communication between two docker compose projects
running two docker-compose projects on localhost
developing especially Django apps or Django Rest Framework (drf) API and running app inside container on some exposed port
And you want to

container api_a communicate to api_b (or vice versa) without the same “docker network”
(example below)

you can use “host” of the second container as IP of your computer and port that is mapped from inside Docker container. You can obtain IP of your computer with this script (from: Finding local IP addresses using Python’s stdlib):

import socket
def get_ip():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
# doesn’t even have to be reachable
s.connect((‘10.255.255.255’, 1))
IP = s.getsockname()[0]
except:
IP = ‘127.0.0.1’
finally:
s.close()
return IP
Example:

project_api_a/docker-compose.yml:

networks:
app-tier:
driver: bridge

services:
api:
container_name: api_a
image: api_a:latest
depends_on:
- postgresql
networks:
- app-tier
inside api_a container you are running Django app: manage.py runserver 0.0.0.0:8000

and second docker-compose.yml from other project:

project_api_b/docker-compose-yml :

networks:
app-tier:
driver: bridge

services:
api:
container_name: api_b
image: api_b:latest
depends_on:
- postgresql
networks:
- app-tier
inside api_b container you are running Django app: manage.py runserver 0.0.0.0:8001

And trying to connect from container api_a to api_b then URL of api_b container will be: http://<get_ip_from_script_above>:8001/

It can be especially valuable if you are using even more than two(three or more) docker-compose projects and it’s hard to provide common network for all of it - it’s good workaround and solution