Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connect two docker containers

I have two containers, the first one with a django and the second one with postgresql.

Well, in my first server I have running django and I'm trying to connect it with the second one. The second container has the port 32770 exposed but internally running in the port 5432. In my local machine, I have the connection: Server: 'Localhost' Port: 32770 User: 'myuser' Password: ''

And it's connecting, but with my django container, I'm getting this error:

could not connect to server: Connection refused
    Is the server running on host "localhost" (127.0.0.1) and accepting
    TCP/IP connections on port 32770?

The same happens for the port 5432

How I can connect both servers?

like image 325
Benjamin RD Avatar asked Jan 04 '23 10:01

Benjamin RD


1 Answers

Since your are running the containers individually you have different options

Run django on network of postgres container

$ docker run -d ... postgres
<container id>

$ docker run -d ... --net container:<containerid> django

Then django can find postgres on localhost:5432

Run django and postgres as named containers container

$ docker run --name postgresdb -d ... postgres
<container id>

$ docker run -d ...  django

Now django can find db on postgresdb:5432

Run both containers on host

$ docker run --net host -d ... postgres
<container id>

$ docker run -d ... --net host django

Then django can find postgres on localhost:5432

Run containers on same network

$ docker network create mynet

$ docker run --name postgresdb --net mynet -d ... postgres
<container id>

$ docker run --net mynet -d ...  django

Now django can find db on postgresdb:5432

Connect to the host IP and mapped port

$ docker run -d -p 32770:5432 .... postgres

$ docker run -d .... django

Django can now connect to the DB on <yourdockerhostip>:32770.

Better option is to run it using docker-compose. Learn more on https://docs.docker.com/compose/

like image 152
Tarun Lalwani Avatar answered Jan 06 '23 00:01

Tarun Lalwani