Skip to content

Docker container networking for microservices

Docker container networking is the configuration that enables communication between different containers, such as a Go microservice and a Redis database.^[part-5.database.redis__readme.md] Because containers operate in isolation, specific network configurations are required to allow them to exchange data while maintaining separation from the host and other networks^[part-5.database.redis__readme.md].

Networking Drivers

Docker uses specific drivers to manage container connectivity. In the provided example, a custom network named redis is created using the --net redis flag during container instantiation^[part-5.database.redis__readme.md]. This network serves as a communication bridge, allowing the application container to resolve and connect to the database containers running on the same logical network segment^[part-5.database.redis__readme.md].

Configuration via Environment Variables

To facilitate service discovery and authentication within the network, containers rely on environment variables passed at runtime^[part-5.database.redis__readme.md]. For a service connecting to a distributed database like Redis Sentinel, these variables typically define:

  • Sentinel Addresses: A comma-separated list of sentinel hostnames (e.g., sentinel-0:5000).
  • Master Name: The alias of the master instance (e.g., mymaster).
  • Credentials: Passwords for secure access^[part-5.database.redis__readme.md].

The application code reads these variables to establish a connection client, ensuring that the microservice can locate and authenticate with the database backend dynamically^[part-5.database.redis__readme.md].

Implementation Example

The following docker run command demonstrates launching a Go microservice container configured to join the redis network and connect to a Redis cluster^[part-5.database.redis__readme.md]:

docker run -it -p 80:80 `
  --net redis `
  -e REDIS_SENTINELS="sentinel-0:5000,sentinel-1:5000,sentinel-2:5000" `
  -e REDIS_MASTER_NAME="mymaster" `
  -e REDIS_PASSWORD="a-very-complex-password-here" `
  videos

This command maps port 80, attaches the container to the redis network, and injects the necessary configuration details for the application to interact with the database^[part-5.database.redis__readme.md].

Sources

^[part-5.database.redis__readme.md]