正确的 IP 地址以访问 apache docker 容器中的 Web 应用程序

Correct IP address to access web application in apache docker container

我在 docker-compose.yml:

中定义了一个简单的 apache docker 设置
services:
    apache: 
        image: php:7.4-apache
        command: /bin/bash -c "/var/www/html/startup.sh && exec 'apache2-foreground'"
        volumes:
            - ./:/var/www/html
            - /c/Windows/System32/drivers/etc/hosts:/tmp/hostsfile
        ports:
            - "80:80"

startup.sh 脚本我想通过卷修改来自主机 OS 的 hosts 文件。在这里,我想动态添加一个条目来将主机名 test.local 解析为 docker Web 应用程序的 IP 地址,如下所示:

<ip-address> test.local

这样我应该能够在我的本地浏览器中打开具有指定主机名 http://test.local 的应用程序。


在编写 startup.sh 脚本之前,我想尝试通过从

获得的容器 IP 地址手动打开位于 http://172.19.0.2 的应用程序
docker inspect apache_test

但是页面打不开:ERR_CONNECTION_TIMED_OUT

我不应该能够从该 IP 访问该应用程序吗?我错过了什么?我是否使用了错误的 IP 地址?

顺便说一句:我正在使用 Docker 桌面 Windows 和 Hyper-V 后端

Edit:我可以通过 http://localhost 访问该应用程序,但是因为我想向 hosts 文件添加一个新条目,所以这不是解决方案。

显然in newer versions of Docker Desktop for Windows you can't access (ping) your linux containers by IP

现在有一些really dirty workaround for this that involves changing a .ps1 file of your Docker installation to get back the DockerNAT interface on windows. After that you need to add a new route in your windows routing table as described here:

route /P add <container-ip> MASK 255.255.0.0 <ip-found-in-docker-desktop-settings>

然后您可以从 windows 主机 ping 您的 docker 容器。虽然我没有测试它...


我在阅读上面 here

上链接的其中一个线程时找到了我的原始问题的解决方案(通过 hosts 文件将 test.local 解析为容器 IP)

这涉及在 docker-compose.yml:

ports 部分的 127.0.0.0/8 IP 范围内设置一个免费环回 IP
ports:
    - "127.55.0.1:80:80"

之后,将以下内容添加到 hosts 文件中:

127.55.0.1 test.local

您可以在 http://test.local

打开您的应用程序

要为其他 docker 化的应用程序做到这一点,只需选择另一个免费环回地址即可。