skip to Main Content

Im trying to redirect to docker containers using nginx but when accessing my server from an ‘external pc'(host and other vagrant machines) the address doesn’t resolve. I have passed ‘host.docker.internal:172.17.0.1’ to the containers host file but still no success. Im testing this using vagrant. The server is running Ubuntu Server 21.10 and curling the address from here works.

default nginx conf:

server {
listen       80;
listen  [::]:80;
server_name  localhost;
    
#access_log  /var/log/nginx/host.access.log  main;
location /dockercontainer_1 {
    return 301 http://host.docker.internal:79;
}

location /dockercontainer_2 {
    return 301 http://host.docker.internal:34;
}

#error_page  404              /404.html;

# redirect server error pages to the static page /50x.html
#
error_page   500 502 503 504  /50x.html;
location = /50x.html {
    root   /usr/share/nginx/html;
}
}

nginx container host file:

127.0.0.1       localhost
::1     localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
172.17.0.1      host.docker.internal
172.17.0.4      35fced58d2eb

Ubuntu Server hosts file:

127.0.0.1 localhost
127.0.1.1 vagrant
127.0.0.1 host.docker.internal
# The following lines are desirable for IPv6 capable hosts
::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

2

Answers


  1. to access containers from external machine you need to tell nginx to serve on your public ip address so just edit the forth line of default nginx config file :

    this line:

      server_name localhost;
    

    To this:

      server_name 127.0.0.1  localhost;
    

    change 127.0.0.1 to the public ip address of your machine.

    Login or Signup to reply.
  2. Lets say that you initiate 2 nginx container with the following command

    docker container run -d --name dockercontainer1 -p 8081:80 nginx
    docker container run -d --name dockercontainer2 -p 8082:80 nginx
    

    Then you should edit your localtion block in the host machine

    location /dockercontainer_1 {
        return 301 http://localhost:8081;
    }
    
    location /dockercontainer_2 {
        return 301 http://localhost:8082;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search