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>80/tcp   webserver

on my windows host I have a Spring Boot application running at port 10090:
netstat -an | grep 10090
  TCP              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                 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):
Ethernet adapter Ethernet:
If I try:
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.


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

No comments: