Docker Tutorial

18.Docker Container Linking | Connect Containers for Communication

Docker – Container Linking

Container linking allows Docker containers to communicate with each other, share environment variables, and connect services. While modern Docker networking often replaces the need for links, understanding container linking helps with legacy applications.

What is Container Linking?

Container linking creates a secure connection between two or more containers. It allows one container to access another container’s exposed ports and environment variables without exposing them to the host network.

Creating a Linked Container


# Run a database container
docker run -d --name mydb mysql:5.7

# Run a web container linked to the database container
docker run -d --name myweb --link mydb:db nginx

How Links Work

  • Docker automatically adds environment variables for the linked container.
  • The alias provided (like db above) can be used inside the container to connect to the linked service.
  • Links create a private network connection between containers.

Accessing Linked Containers

Inside the myweb container, you can access the database using the alias db and the standard MySQL port:


# Connect to MySQL container from myweb container
mysql -h db -u root -p

Best Practices for Container Linking

  • Prefer custom Docker networks over links for new projects, as links are considered legacy.
  • Use meaningful aliases for easier identification.
  • Keep services isolated and expose only necessary ports.
  • Monitor linked containers to ensure connectivity and availability.
  • Document container dependencies and relationships clearly.

Conclusion

Container linking helps containers communicate and share services. While modern Docker networking is more flexible, understanding linking is useful for maintaining legacy container setups and simpler inter-container communication.

Leave a Reply

Your email address will not be published. Required fields are marked *