Every container is accessible through its own IP address. For instance, we can find the IP address of our elasticsearch-oss container by running docker inspect, and looking under NetworkSettings.IPAddress:
$ docker inspect a415f4b646e3
[
{
"Id": "a415f4b646e3a71...81b9b7f6dcaf76b",
"Created": "2018-05-10T19:37:55.565685206Z",
"Image": "sha256:3822ba554fe9...adf11f6a59bde0139",
"Name": "/elasticsearch",
"Driver": "overlay2",
"NetworkSettings": {
"Ports": {
"9200/tcp": [{
"HostIp": "0.0.0.0",
"HostPort": "9200"
}],
"9300/tcp": [{
"HostIp": "0.0.0.0",
"HostPort": "9300"
}]
},
"Gateway": "172.17.0.1",
"IPAddress": "172.17.0.2",
...
}
...
}
]
You can also use the --format or -f flag to retrieve only the field you are interested in:
$ docker inspect -f '{{.NetworkSettings.IPAddress}}' elasticsearch
172.17.0.2
However, our local instance of our API assumes that Elasticsearch is available on localhost:9200, not 172.17.0.2. If we are going to provide an equivalent behavior to our non-containerized Elasticsearch, we must make Elasticsearch available on localhost:9200. That’s the job of the -p flag.
The -p flag publishes a port of the container and binds it to the host port:
$ docker run -p <host-port>:<container-port>
In our case, we are binding the 9200 port of 0.0.0.0 to the 9200 port of the container. 0.0.0.0 is a special address that refers to your local development machine.