簡體   English   中英

如何使用 nginx 將地址重定向到另一個 docker 容器?

[英]How do I redirect an address to another docker container using the nginx?

我嘗試使用 nginx 重定向到 docker 容器,但是當從“外部 pc”(主機和其他 vagrant 機器)訪問我的服務器時,地址無法解析。 我已將“host.docker.internal:172.17.0.1”傳遞給容器主機文件,但仍然沒有成功。 我正在使用 vagrant 對此進行測試。服務器正在運行 Ubuntu Server 21.10 並且可以從此處卷曲地址。

默認 nginx 配置文件:

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 容器主機文件:

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 服務器主機文件:

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

要從外部機器訪問容器,您需要告訴 nginx 在您的公共ip地址上提供服務,因此只需編輯默認 nginx 配置文件的第四行:

這一行:

  server_name localhost;

對此:

  server_name 127.0.0.1  localhost;

127.0.0.1更改為您機器的公共 ip 地址。

假設您使用以下命令啟動 2 nginx 容器

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

然后你應該在主機中編輯你的 localtion 塊

location /dockercontainer_1 {
    return 301 http://localhost:8081;
}

location /dockercontainer_2 {
    return 301 http://localhost:8082;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM