Docker Networking

Understand how Docker handles networking and how to configure networks to enable seamless container communication.

Types of Docker Networks

Docker supports multiple network drivers, each designed for different use cases:

  • bridge: The default network for containers. Suitable for local communication on a single host.
  • host: Shares the host’s network stack. Useful for performance-critical applications.
  • none: Disables all networking. Ideal for isolated containers.
  • overlay: Enables communication across multiple Docker hosts. Used with Docker Swarm.
  • macvlan: Assigns a MAC address to containers for them to appear as physical devices on the network.

Connecting Containers Using Custom Networks

Creating a user-defined bridge network allows containers to discover and communicate with each other using container names as hostnames.

Example:

docker network create my_custom_network

When you run containers in this network:

docker run -d --name app --network my_custom_network my_app_image

docker run -d --name db --network my_custom_network my_db_image

The app container can communicate with the db container by simply using db as the hostname.

Exposing Container Ports

To allow external access to a container's service, you need to expose its port using the -p flag:

docker run -p 8080:80 my_web_image

This maps port 80 inside the container to port 8080 on the host. Now, you can access the service at http://localhost:8080.

Multiple port mappings can be specified to expose different services or protocols.

Post a Comment

0 Comments