Correct IP address to access web application in apache docker container

时间秒杀一切 提交于 2021-02-11 12:48:58

问题


I have an easy apache docker setup defined in a docker-compose.yml:

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"

From the startup.sh script I want to modify the hosts file from the host OS through the volume. Here I want to dynamically add an entry to resolve the hostname test.local to the ip address of the docker web application like so:

<ip-address> test.local

This way I should be able to open the application with the specified hostname http://test.local in my local browser.


Before writing the startup.sh script I wanted to try to manually open the application at http://172.19.0.2 via the containers IP address I got from

docker inspect apache_test

But the page won't open: ERR_CONNECTION_TIMED_OUT

Shouldn't I be able to access the application from that IP? What am I missing? Do I use the wrong IP address?

BTW: I am using Docker Desktop for Windows with the Hyper-V backend

Edit: I am able to access the application via http://localhost but since I want to add a new entry to the hosts file this is not the solution.


回答1:


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

Now there is some 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>

Then you might be able to ping your docker container from the windows host. I didn't test it though...


I found a solution to my original issue (resolution of test.local to container IP via hosts file) while reading one of the threads linked above here

That involves setting a free loopback IP in the 127.0.0.0/8 IP range in your ports section of the docker-compose.yml:

ports:
    - "127.55.0.1:80:80"

After that you add the following to your hosts file:

127.55.0.1 test.local

And you can open your application at http://test.local

To do that for other dockerized applications too just choose another free loopback address.



来源:https://stackoverflow.com/questions/66026454/correct-ip-address-to-access-web-application-in-apache-docker-container

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!