3

I create an Docker's image with name is sample, then I installed nginx on both of them that listen to port 80 and it shows simple index.html.

then I use below commands to run contianers:

 docker run -it -p 80:80 --name sample1 sample
 docker run -it -p 81:80 --name sample2 sample

and I successfully see the index.html from main OS from two containers, but when I go inside container sample1 I couldn't see the index.html of sample2 and It does not work conversely either.

AKZ
  • 856
  • 2
  • 12
  • 30

2 Answers2

2

The -p option is the shortform for ports. When you do -p you are binding the container's port 80 to its host's port 80.

So container sample1 and sample2 are just merely binding their respective port 80 to the host's port 80 and 81, hence there is no direct linkage between them.

To make the containers visible to each other, first you will have to use the --link option and then do an --expose to allow the containers to see each other through the exposed port.

Example:

docker run -it -p 80:80 --name sample1 sample
docker run -it -p 81:80 --link=sample1 --expose="80" --name sample2 sample

Essentially --link means to allow the container to see the link value's container

--expose means the linked containers are able to communicate through that expose port.

Note: linking the containers is not sufficient, you need to expose ports for them to communicate.

You might want refer to the docker-compose documentation for more details; https://docs.docker.com/compose/compose-file/

While the documentation is for docker-compose but the options are pretty much the same as the raw docker binary, and everything is nicely put on 1 page. That's why I prefer looking at there.

Samuel Toh
  • 18,006
  • 3
  • 24
  • 39
  • Supposingly you are trying to access container 2's web from container 1 then u need to know container2's IP address then port 80 – Samuel Toh Jul 13 '16 at 07:55
  • yes, I'm trying to access container 2's web from container 1, but both of them on the same machine and the machine IP address is 192.168.4.150 – AKZ Jul 13 '16 at 08:03
  • Yes they are on the same machine but their IP address will be different thou. See http://stackoverflow.com/questions/17157721/getting-a-docker-containers-ip-address-from-the-host – Samuel Toh Jul 13 '16 at 08:27
0

In Docker you can bind container's port to docker machine (Machine installed with docker) port using

docker run -it -p 80:80 image

Then you can use docker machine Ip and port inside the another container.

Vigneshwaran
  • 782
  • 2
  • 7
  • 22