Docker直接访问容器IP /端口

Docker access container IP/Port directly

我有实验用的码头集装箱。因此,我不知道稍后在尝试新应用程序时将使用哪些端口。在不在docker run命令中公开的情况下,是否可以从主机访问具有IP/端口的docker容器应用程序?


Docker for Mac is unable to route traffic to containers, and from containers back to the host.

https://docs.docker.com/docker for mac/networking/i-cannot-ping-my-containers


更新:OP没有在原来的问题中提供关于docker-for-mac的内容,所以如果您使用这个版本的docker,其余的内容就不能应用了。

原始答案:

是的,你能做到。

假设您有一个名为boring_pare的容器和一个运行在8080端口上的Web应用程序。您可以通过请求http://[ip_of_boring_pare]:8080从主机访问它。如果您使用默认的Docker网络,则此IP可能在172.17.0.xxx范围内。

要找到此IP,您可以使用以下方法来inspect您的容器:

1
docker container inspect boring_pare

此外,您还提到:

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

这里的正确术语是出版。进一步阅读:

  • 关于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.

  • Docker中"公开"和"发布"的区别

@robie2011评论回复更新:

下面,我运行3个命令:

  • 在不将port 80发布到host端口的情况下运行nginx容器
  • 检查其ip address
  • 使用host中的curl访问nginx主页
  • 我的控制台输出:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    $ 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>
    Welcome to nginx!
    <style>
        body {
            width: 35em;
            margin: 0 auto;
            font-family: Tahoma, Verdana, Arial, sans-serif;
        }
    </style>
    </head>
    <body>
    Welcome to nginx!
    <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
    nginx.org.<br/>
    Commercial support is available at
    nginx.com.
    </p>

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