如何使用 nginx 設定反向代理?

如何使用 nginx 設定反向代理?

我正在嘗試獲取我的 docker 容器的主機名,並且因為我只能使用反向代理為此,我試圖在 nginx 的幫助下實現這一目標。

一個 docker 容器是一個 Web 服務,它將連接埠 8080 公開給我的本機。

所以我可以透過以下方式存取網頁伺服器:

http://localhost:8080

相反,我寧願使用:

http://webservice.local

因此我添加到我的/etc/hosts

127.0.0.1 webservice.local

然後我安裝了 nginx 並添加到/etc/nginx/sites-available/default

server {
     listen 80 default_server;
     listen [::]:80 default_server ipv6only=on;

     root /usr/share/nginx/html;
     index index.html index.htm;

     # Make site accessible from http://localhost/
     server_name localhost;

     location / {
             # First attempt to serve request as file, then
             # as directory, then fall back to displaying a 404.
             try_files $uri $uri/ =404;
             # Uncomment to enable naxsi on this location
             # include /etc/nginx/naxsi.rules
     }


     location webservice.local {
         proxy_pass http://localhost:8080
     }

重新載入 nginx 後,嘗試在瀏覽器中 ERR_CONNECTION_REFUSED開啟時出現以下錯誤。http://webservice.local

我做錯了什麼?如何正確設定反向代理?

答案1

我不確定這是正確的語法。試試這樣的事情:

upstream myupstream {
    server 127.0.0.1:8080 fail_timeout=2s;
    keepalive 32;
}

location / {
     proxy_pass http://myupstream;
     proxy_redirect http://myupstream/ /;
}

沿著這些思路的東西..

但是,如果您只想將連接埠 8080 重定向到 80,為什麼不使用像 socat 這樣的網路實用程式呢?

然後,您應該在 nginx 中為每個上游新增虛擬主機,並在 DNS 或 /etc/hosts 中新增這些虛擬主機,這些虛擬主機都會解析為 localhost。

或者你可以避免上游並使用虛擬主機,如下所示:

server {
  listen 80;
  server_name myvirtualhost1.local;
  location / {
    proxy_pass http://127.0.0.1:8080;
}

server {
  listen 80;
  server_name myvirtualhost2.local;
  location / {
    proxy_pass http://127.0.0.1:9090;
}

相關內容