Saturday, March 18, 2023

Docker container connecting to host service on Windows

docker run -d -p 80:80 --name webserver nginx
docker ps
CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS          PORTS                NAMES
2733688156aa   nginx     "/docker-entrypoint.…"   14 seconds ago   Up 13 seconds   0.0.0.0:80->80/tcp   webserver


on my windows host I have a Spring Boot application running at port 10090:
netstat -an | grep 10090
  TCP    0.0.0.0:10090          0.0.0.0:0              LISTENING
  TCP    [::]:10090             [::]:0                 LISTENING
  TCP    [::1]:53110            [::1]:10090            TIME_WAIT
  TCP    [::1]:53123            [::1]:10090            TIME_WAIT
  TCP    [::1]:53126            [::1]:10090            TIME_WAIT

and I can also see the nginx container
netstat -an | grep 80
  TCP    0.0.0.0:80             0.0.0.0:0              LISTENING
  TCP    [::]:80                [::]:0                 LISTENING
  TCP    [::1]:80               [::]:0                 LISTENING


If in browser you type "localhost" you should get nginx welcome page (at port 80, default)

Now log into container:
docker exec -it webserver sh

from the container you can connect to
curl host.docker.internal
curl host.docker.internal:10090
they both work, because they "resolve to the internal IP address used by the host"
On my Windows host, if I type "ipconfig" I see that I have
Ethernet adapter vEthernet (WSL): 172.28.176.1
Ethernet adapter Ethernet: 192.168.0.248
If I try:
curl 172.28.176.1:10090
curl 192.168.0.248:10090
they both work on both host and container, but the first is a lot more responsive.
This proves that from container you can access a service running on host.

References:

http://man.hubwiz.com/docset/Docker.docset/Contents/Resources/Documents/docs.docker.com/docker-for-windows/networking.html

NB: besides host.docker.internal , also docker.for.win.localhost can be used, but they have different values (which?)

No comments: