Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to connect two docker containers through localhost?

I have two services running in separate containers, one is grunt(application) and runs off port 9000 and the other is sails.js (server) which runs off port 1337. What I want to try to do is have the client app connect with the server through localhost:1337. Is this feasible? Thanks.

like image 664
reconman Avatar asked Mar 19 '15 11:03

reconman


People also ask

How do I access Docker on localhost?

Accessing the Host With the Default Bridge Mode You just need to reference it by its Docker network IP, instead of localhost or 127.0. 0.1 . Your host's Docker IP will be shown on the inet line. Connect to this IP address from within your containers to successfully access the services running on your host.

Can two containers run on same port?

So there is no conflict if multiple containers are using the same port ( :80 in this case). You can access one container from another using its container-name or service-name or ip-address, whereas ip-address is not a good idea because this might change every time you (re)start the container.


1 Answers

HOST

You won't be able to connect to the other container with localhost (as localhost is the current container) but you can connect via the container host (the host that is running your container). In your case you need boot2docker VM IP (echo $(boot2docker ip)). For this to work, you need to expose your port at the host level (which you are doing with -p 1337:1337).

LINK

Another solution that is most common and that I prefer when possible, is to link the containers.

You need to add the --name flag to the server docker run command: --name sails_server

You need to add the --link flag to the application docker run command: --link sails_server:sails_server

And inside your application, you will be able to access the server at sail_server:1337 You could also use environment variables to get the server IP. See documentation: https://docs.docker.com/userguide/dockerlinks/

BONUS: DOCKER-COMPOSE

Your run commands may start to be a bit long... in this case I like to use docker-compose that allows me to define my containers and their relationships (volumes, names, link, commands...) in one file.

like image 89
Céline Aussourd Avatar answered Sep 23 '22 21:09

Céline Aussourd