[Docker] Bind 2 standalone containers by docker network

R4 Cheng
1 min readFeb 22, 2024

--

Photo by Shubham Dhage on Unsplash
  • A common use case is to connect the app and DB at local

I think when the app is deployed to cloud, we do not need this method and should follow the instruct of the cloud service

Issue: both containers are running but the connection between each other is refused

Run docker container inspect <container_name> to see bridge IPAddress of the container. You may find out that your source container IP address setting to the target container is wrong (E.g you connect to localhost)

{
...,
"Networks": {
"bridge": {
"IPAddress": "172.17.0.3"
}
}
}

Solutions

  1. (Quick but not recommended) Connect to the IPAddress the target container gives
  2. Use user-defined network

Step 1: Run docker network create <new_network_name> to create a new network

Step 2: Run docker network connect <new_network_name> <container_to_bind> for the two standalone containers

Step 3: Run docker network inspect <new_network_name> to check

Run docker network ls can see all networks

Step 4: Change the connection IP address to the target container name.

E.g to connect to postgreSQL container

docker run --name <app_name> -e DB_SOUCE = "postgresql://<account>:<password>@172.17.0.3:5432"

Now you can change 172.17.0.3 to the name of the target container:

docker run --name <app_name> -e DB_SOUCE = "postgresql://<account>:<password>@<target_container_name>:5432"

--

--

R4 Cheng
R4 Cheng

Written by R4 Cheng

「0」が過去で「1」が未来「今」は何処にもない

No responses yet