Networking in Docker

Networking in Docker

Introduction

Docker networking allows containers to communicate with each other and with the outside world. It enables isolation, connectivity, and scalability for containerized applications.

1️Types of Docker Networks

Docker provides several types of networks, each designed for specific use cases.

A) Bridge Network (Default for Standalone Containers)

  Allows containers to communicate on the same host.
  Containers in the bridge network can talk to each other via container names.

✅ Create a container in the default bridge network:

docker run -d –name my_app nginx

✅ List available networks:

docker network ls

✅ Connect a container to a specific bridge network:

docker network connect bridge my_app

B) Host Network (Uses the Host’s Network Stack)

  Removes network isolation between the container and the host.
  The container uses the host’s network directly.

✅ Run a container using the host network:

docker run -d –network host nginx

⚠️ Not available on Windows due to networking differences.

C) None Network (No Networking)

  Fully isolates the container from the network.

✅ Run a container with no network access:

docker run -d –network none nginx

D) Custom User-Defined Networks

  Allows better container-to-container communication.
  Containers can reference each other by container name instead of IP addresses.

✅ Create a custom network:

docker network create my_network

✅ Run a container in a custom network:

docker run -d –network my network –name app1 nginx

docker run -d –network my network –name app2 alpine sleep 3600

✅ Test container-to-container communication:

docker exec -it app2 ping app1

If ping is successful, the containers are connected!

2️. Networking in Docker Compose

In Docker Compose, networking is automatic.

Example docker-compose.yml:

yaml

version: ‘3’

services:

  web:

    image: nginx

    networks:

      – my network

 

  database:

    image: mysql

    networks:

      – my_network

 

networks:

  my_network:

Containers inside the same Docker Compose network can communicate using their service names (web, database).

✅ Run the Compose setup:

docker-compose up -d

3️. Inspecting & Managing Networks

✅ Inspect a network’s details:

docker network inspect my_network

✅ Disconnect a container from a network:

docker network disconnect my_network app1

✅ Remove a network:

docker network rm my_network

Conclusion

  Bridge networks are the default and work for most cases.
•  Host networks provide better performance but reduce isolation.
  Custom networks help organize multi-container applications.
  Docker Compose simplifies container networking.

Chatbot