Docker access container IP/Port directly

robie2011 picture robie2011 · Nov 13, 2017 · Viewed 12k times · Source

I have docker container for experiments. So I don't know which ports I will use later when I trying new apps. Isn't it possible to access docker container application with ip/port from the host without exposing it in the docker-run command?

Answer

tgogos picture tgogos · Nov 13, 2017

update: the OP didn't provide that it was about docker-for-mac in the original question, so the rest cannot be applied if you are using this version of docker.


Original answer:

Yes, you can do that.

Let's say that you have a container named boring_pare and a web app running on port 8080. You can access it from your host machine by requesting http://[ip_of_boring_pare]:8080. If you are using the default docker network, this ip will probably be in the 172.17.0.xxx range.

To find this IP, you can inspect your container by using:

docker container inspect boring_pare

Also, you mention:

Isn't it possible to access docker container application with ip/port from the host without exposing it in the docker-run command?

The correct term here would be publishing. Further reading:

  • Documentation about EXPOSE / Dockerfile

    ...The EXPOSE instruction does not actually publish the port. It functions as a type of documentation between the person who builds the image and the person who runs the container, about which ports are intended to be published. To actually publish the port when running the container, use the -p flag on docker run to publish and map one or more ports, or the -P flag to publish all exposed ports and map them to to high-order ports.

  • Difference between “expose” and “publish” in docker


Update to answer to @robie2011's comment:

Below, I run 3 commands:

  1. run a nginx container without publishing port 80 to a host port
  2. inspect its ip address
  3. use curl from host to access the nginx home page

My console output:

$ docker run --rm --name some-nginx -d nginx
0e53d3b5ef6d65a4731c4066f3523c5ecd3c118abedae44b33e89fdf8e401632

$ docker container inspect --format '{{ .NetworkSettings.IPAddress }}' some-nginx
172.17.0.3

$ curl 172.17.0.3
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>
$