Docker Networking
Docker networking allows containers to communicate with each other and with the outside world. Understanding Docker networking concepts and knowing how to connect containers is essential when building complex applications with multiple services.
Default Bridge Network
When you run a container, Docker creates a default bridge network named bridge
. This network allows containers to communicate with each other using IP addresses within the same network subnet. Docker assigns an IP address to each container within the bridge network.
For example, let's say we have two containers running in Docker:
1const frontendContainer = {
2 name: 'frontend',
3 ip: '172.18.0.2'
4};
5
6const backendContainer = {
7 name: 'backend',
8 ip: '172.18.0.3'
9};
In this case, Docker assigns the IP address 172.18.0.2
to the frontend
container and 172.18.0.3
to the backend
container within the bridge
network.
Containers can communicate with each other using their IP addresses. For example, the frontend
container can connect to the backend
container by using its IP address, and vice versa.
1console.log(`${frontendContainer.name} IP: ${frontendContainer.ip}`);
2console.log(`${backendContainer.name} IP: ${backendContainer.ip}`);
3
4// Output:
5// frontend IP: 172.18.0.2
6// backend IP: 172.18.0.3
7
8console.log(`${frontendContainer.name} can connect to ${backendContainer.name}`);
9console.log(`${backendContainer.name} can connect to ${frontendContainer.name}`);
10
11// Output:
12// frontend can connect to backend
13// backend can connect to frontend
xxxxxxxxxx
// Let's say we have two containers running in Docker
const frontendContainer = {
name: 'frontend',
ip: '172.18.0.2'
};
const backendContainer = {
name: 'backend',
ip: '172.18.0.3'
};
// To enable networking between the containers,
// Docker creates a default bridge network
const bridgeNetwork = {
name: 'bridge',
subnet: '172.18.0.0/16'
};
// Each container is assigned an IP address within the network
console.log(`${frontendContainer.name} IP: ${frontendContainer.ip}`);
console.log(`${backendContainer.name} IP: ${backendContainer.ip}`);
// Containers can communicate using their IP addresses
console.log(`${frontendContainer.name} can connect to ${backendContainer.name}`);
console.log(`${backendContainer.name} can connect to ${frontendContainer.name}`);