Docker container Networking for Go and Redis¶
When building applications with Docker, networking between containers is a fundamental requirement, especially when separating services like a Go web application and a Redis database.
Core Networking Configuration¶
For a Go application to communicate with a Redis instance, both containers must exist on the same Docker network^[400-devops__09-Scripting-Language__golang__introduction__part-5.database.redis__readme.md]. If Redis is started on a specific network (e.g., a network named redis), the Go application container must be attached to that same network using the --net flag during startup^[400-devops__09-Scripting-Language__golang__introduction__part-5.database.redis__readme.md].
Service Discovery and Addressing¶
Once containers are on the same network, the Go application can reach the Redis service using the container names or hostnames of the Redis nodes, rather than raw IP addresses^[400-devops__09-Scripting-Language__golang__introduction__part-5.database.redis__readme.md].
For example, in a Redis Sentinel Configuration, environment variables should define the addresses of the Sentinel containers using their names:
-e REDIS_SENTINELS="sentinel-0:5000,sentinel-1:5000,sentinel-2:5000"
In this configuration, sentinel-0, sentinel-1, and sentinel-2 resolve to the respective containers within the Docker network^[400-devops__09-Scripting-Language__golang__introduction__part-5.database.redis__readme.md].
Configuration via Environment Variables¶
Best practices involve passing connection details as environment variables to the Go container. This keeps the code generic and the configuration dynamic^[400-devops__09-Scripting-Language__golang__introduction__part-5.database.redis__readme.md]. Common variables include:
- REDIS_SENTINELS: A comma-separated list of Sentinel addresses.
- REDIS_MASTER_NAME: The alias of the Redis master group (e.g.,
mymaster). - REDIS_PASSWORD: The authentication password.
The Go application reads these variables to initialize the Redis client connection^[400-devops__09-Scripting-Language__golang__introduction__part-5.database.redis__readme.md].
Related Concepts¶
- Dockerfile
- [[Environment Variables]]
- [[Go Redis Client]]
Sources¶
400-devops__09-Scripting-Language__golang__introduction__part-5.database.redis__readme.md