Skip to content

Docker - Container Linking

Docker - Container Communication (User Networks)

Section titled “Docker - Container Communication (User Networks)”

In modern Docker workflows, the recommended way for containers to communicate with each other is by connecting them to the same user-defined network. This provides automatic service discovery using container names.

The older --link flag is now considered legacy and deprecated. User-defined networks offer better isolation, security, and flexibility.

Example: Connecting a Web App to a Database

Section titled “Example: Connecting a Web App to a Database”

Let’s illustrate how to connect two containers (e.g., a web application and a Redis database) using a user-defined bridge network.

Step 1: Create a user-defined bridge network. We’ll call it app-network.

docker network create app-network

Step 2: Start the database container (e.g., Redis) and attach it to the app-network. We’ll name this container redis-db.

# Start Redis container detached (-d), named 'redis-db', on 'app-network'
docker run -d --name redis-db --network app-network redis:alpine

Step 3: Start the application container (e.g., a hypothetical web app image my-web-app) and attach it to the same app-network. We’ll name it web-frontend and publish its port.

# Start web app container detached, named 'web-frontend', on 'app-network'
# Map host port 80 to container port 8080 (assuming the app listens on 8080)
docker run -d --name web-frontend --network app-network -p 80:8080 my-web-app

Now, inside the web-frontend container, the application code can connect to the Redis database simply by using the hostname redis-db. Docker’s embedded DNS server automatically resolves redis-db to the correct internal IP address of the Redis container within the app-network.

For example, the connection string in the web application might look like redis://redis-db:6379.

Step 4: You can verify connectivity by running a temporary container on the same network and trying to ping the database container by name.

# Run a temporary Ubuntu container on app-network, get a shell
docker run -it --rm --network app-network ubuntu bash
# Inside the Ubuntu container, install ping (if needed) and ping 'redis-db'
# apt-get update && apt-get install -y iputils-ping
# ping redis-db

You should see successful ping responses, confirming that name resolution is working within the user-defined network.

Using user-defined networks is the standard, robust way to handle inter-container communication in Docker, simplifying application configuration and enhancing security.