Connecting Docker Containers: link, net host, net container, and Custom Networks
This article demonstrates several methods for enabling a web container to communicate with a Redis container in Docker, covering the deprecated link approach, three net-based techniques, and the recommended custom network solution, while highlighting their advantages and limitations.
Assume a web application needs to display the total number of connections stored in a Redis service; the web container must connect to the Redis container. Because each Docker container has its own virtual network, special connection methods are required.
Step 1: Start a Redis container
docker run --name redis redis
Step 2: Start the web container using the --link option
--link redis:redis_connection
Inside the web program, the alias redis_connection can be used to reach Redis. The link method injects environment variables and updates /etc/hosts , allowing name‑based access without specifying an IP address. However, this method is deprecated and will be removed.
Net Method 1
Expose the Redis container’s port to the host and configure the web container to use the host’s IP address. Direct use of localhost inside the web container is invalid because it refers to the container itself.
Net Method 2
Run the web container with --net host , allowing it to access Redis via localhost without exposing ports. This works on Linux hosts but not on macOS, where Docker runs inside a VM, and it also raises security concerns.
Net Method 3
Use --net container to share the network namespace of the Redis container. This avoids port exposure and maintains isolation, but --net container cannot be combined with -p port publishing. One workaround is to publish the required port on the Redis container instead of the web container.
Custom Network (Recommended)
Docker will deprecate link , and the preferred alternative is a user‑defined network.
docker network create -d bridge my-network
Connect both the web and Redis containers to this network, then refer to Redis by its container name. The network can be attached at container start with --net my-network or later with:
docker network connect [network-name] [container]
Custom networks also allow defining subnets, gateways, and IP ranges for more complex scenarios.
The article concludes that the custom network approach is the most practical way to enable container‑to‑container communication.
System Architect Go
Programming, architecture, application development, message queues, middleware, databases, containerization, big data, image processing, machine learning, AI, personal growth.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.