Docker – How to link containers in docker

docker

Here's the result when I type docker ps :
here is the image when i type docker ps

I have 3 docker containers: webapps, redis and rabbitmq. I want to link container webapps to container redis and rabbitmq container. In non docker apps, mywebapps can send message to rabbitmq and write/read redis.

I tried using command like this

docker run --name rabbitmq -p 8080:80 --link webapps:nimmis/apache-php7 -d rabbitmq

but it does not work.

Here is my config.php on webapps where I am trying to send messages via rabbitmq:

define('HOST', 'localhost');
define('PORT', 5672);

I tried to change localhost with hostname

define('HOST', 'rabbitmq');
define('PORT', 5672);

Error message says connection refused.

It seems that in my three containers needs to be configured in the same network namespace.

Best Answer

Linking is a legacy feature. Please use "user defined networks":

sudo docker network create mynetwork

Then rerun your containers using this network:

sudo docker run --name rabbitmq -p 8080:80 -d --network mynetwork rabbitmq

Do the same for other containers that you want connected with each other.

Using "user defined networks", you have an "internal name resolution" at your disposal (somewhat like domain name resolution when visiting websites). You can use the names of the container that you want to refer to, in order to resolve the IP addresses of containers, as long as they are running on the same "user defined network". With this, you can resolve the IP address of the rabbitmq container with its name, within other containers, on the same network.

All containters on the same "user defined network" will have network connectivity. There is no need for "legacy linking".