Container networking with Docker¶
Container networking allows containers running on the same host or across different hosts to communicate with each other and with external systems.^[400-devops-09-scripting-language-golang-introduction-part-5databaseredis-readme.md]
Docker Networks¶
By default, containers are isolated in their own network environments. To enable communication between a containerized application (like a Go web service) and a database (like Redis) running in a separate container, they must be configured to operate on the same Docker network.^[400-devops-09-scripting-language-golang-introduction-part-5databaseredis-readme.md]
Specifying Networks¶
Docker uses the --net flag to assign a container to a specific network namespace during creation.^[400-devops-09-scripting-language-golang-introduction-part-5databaseredis-readme.md] For example, to connect a Go application container to Redis containers running on a redis network, the run command would include:
docker run -it -p 80:80 --net redis my-image sh
Without this configuration, the Go container may be unable to resolve or connect to the Redis instances because they reside on different networks.^[400-devops-09-scripting-language-golang-introduction-part-5databaseredis-readme.md]
Service Discovery¶
Once containers are on the same network, they can communicate using container names as hostnames. Environment variables are often used within the connecting container to specify the address and port of the remote service.^[400-devops-09-scripting-language-golang-introduction-part-5databaseredis-readme.md]
For example, to connect to a cluster of Redis Sentinel instances, the application container might be configured with:
-e REDIS_SENTINELS="sentinel-0:5000,sentinel-1:5000,sentinel-2:5000"
This allows the internal application code to resolve sentinel-0, sentinel-1, etc., to the respective container IP addresses on the shared network.^[400-devops-09-scripting-language-golang-introduction-part-5databaseredis-readme.md]
Related Concepts¶
- [[Dockerfiles]]
- [[Go Microservices]]
- [[Redis Clustering]]
Sources¶
400-devops-09-scripting-language-golang-introduction-part-5databaseredis-readme.md