Nginx 反向代理未使用主机名找到其他内部 Docker 容器

Nginx reverse proxy not finding other internal Docker container using hostname

我有两个 docker 个容器。一个运行 Kestrel (172.17.0.3),另一个运行 Nginx (172.17.0.4),使用反向代理连接到 Kestrel。当我使用 Kestrel 容器的内部 Docker ip 时,Nginx 连接正常,但是当我尝试使用 nginx.conf (kestral) 中的容器主机名连接到 Kestrel 时,出现以下错误:

2020/06/30 00:23:03 [emerg] 58#58: host not found in upstream "kestrel" in /etc/nginx/nginx.conf:7 nginx: [emerg] host not found in upstream "kestrel" in /etc/nginx/nginx.conf:7

我用这两行启动了容器

docker run -d --name kestrel --restart always -h kestrel mykestrelimage
docker run -d --name nginx --restart always -p 80:80 -h nginx mynginximage

下面是我的 nginx.conf 文件。

http {
        # I've tried with and without line below that I found on Whosebug
        resolver 127.0.0.11 ipv6=off;
        server {
                listen 80;
                location / {
                        # lines below don't work 
                        # proxy_pass http//kestrel:80;
                        # proxy_pass http//kestrel
                        # proxy_pass http//kestrel:80/;
                        # proxy_pass http//kestrel/;


                        # when I put internal docker ip of Kestrel server works fine  
                        proxy_pass http://172.17.0.3:80/;
                }
        }
}
events {

}

我找到了解决问题的方法。有两个问题。

第一个问题:默认情况下Docker在创建容器时使用默认桥接网络。默认 Docker 桥接网络不解析 DNS。您必须创建自定义桥接网络,然后在创建 docker 容器时指定网络。下面允许我使用主机名

在容器之间进行 ping
docker network create --driver=bridge mycustomnetwork

docker run -d --name=kestrel --restart=always -h kestrel.local --network=mycustomnetwork mykestrelimage

docker run -d --name=nginx --restart always  -p 80:80 -h nginx.local --network=mycustomnetwork mynginximage

第二个问题:尽管出于某种原因它只是一个 kestrel 服务器 Nginx 要求我在 /etc/nginx/nginx.conf

中设置一个上游部分
http {
        upstream backendservers {
                server kestrel;
        }
        server {
                listen 80;
                location / {
                        proxy_pass http://backendservers/;
                }
        }
}

events {

}