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.
2 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.

- 1
- 1

- 10,214
- 4
- 32
- 36
-
Ah kk, is the sails_server an environment variable or do I just access it directly in my .js file? – reconman Mar 19 '15 at 13:02
-
1@reconman when you link containers, Docker update the `/etc/hosts` file so you can use `sails_server` directly. – Céline Aussourd Mar 19 '15 at 13:44
-
1I'm not satisfied. Is there really no way to achieve the original goal? – Ben May 12 '15 at 05:30
Yes if you use docker parameter -p 1337:1337 in your docker run command, it will expose the port 1337 from inside the container to your localhost:1337

- 1,333
- 1
- 12
- 33
-
1I have tried that, I can access 1337 from the host IP but the application isn't able to connect to localhost:1337. Thanks. – reconman Mar 19 '15 at 12:00
-
1"localhost" inside a container is the container itself. You need to use the IP of the host instead. Or you could just use docker links. – Adrian Mouat Mar 19 '15 at 12:12
-
1are you running docker inside a VM? this is the case if you are using Mac OSX or windows then it runs inside a VM called boot2docker – Mitch Dart Mar 19 '15 at 12:15