Linking Docker containers involves using the `—link` option with the `docker run` command. However, using `—link` option is a legacy feature and may eventually be removed. The recommended way to link containers is through user-defined networks. The advantage of user-defined networks is that you can connect containers across different hosts, something which you cannot do with `—link`.
Here’s an example of how you can link two docker containers using user-defined network:
1. First, you need to create a network:
\`\`\` docker network create my\_network “”“1. Next, you can run a container (for example a mysql container) within this network:
\`\`\` docker run -d —net=my_network —name=my_mysql -e MYSQL_ROOT_PASSWORD=123456 mysql “”“1. You can then run another container within the same network and communicate with the mysql container:
\`\`\` docker run -it —net=my\_network ubuntu bash \`\`\` Once inside this second container, you can connect to mysql using the `my_mysql` host.1. To remove the network, first stop and remove all containers that are using this network, and then remove the network:
\`\`\` docker network rm my\_network \`\`\`In general, Docker recommends using user-defined networks for any scenario where you need containers to communicate on the same Docker host. For more complex scenarios involving multiple Docker hosts, Docker recommends using overlay networks.