2016-10-06 36 views
3

我正在運行安裝了Ubuntu的VPS。如何在不指定URL中的端口(xxx.xxx.xxx.xxx:8084)的情況下使用相同的VPS(相同IP)爲多個Golang網站提供服務?在一個IP上託管多個Golang站點並根據域請求提供服務?

例如,Golang應用程序1正在偵聽端口8084Golang應用2在端口8060偵聽。我希望Golang應用1在有人從域example1.com請求時提供,而Golang應用2則在有人從域example2.com請求時提供。

我敢肯定,你可以使用Nginx的這樣做,但我一直無法弄清楚如何。

+0

https://www.nginx.com/resources/admin-guide/reverse-proxy/ – tkausl

回答

1

請嘗試以下代碼,

server { 
    ... 
    server_name www.example1.com example1.com; 
    ... 
    location/{ 
     proxy_pass app_ip:8084; 
    } 
    ... 
} 

... 

server { 
    ... 
    server_name www.example2.com example2.com; 
    ... 
    location/{ 
     proxy_pass app_ip:8060; 
    } 
    ... 
} 

app_ip是一樣的地方託管,如果在同一臺機器上,把http://127.0.0.1http://localhost

+0

這是用於Nginx的嗎? – Acidic

+0

是的,先生,這是nginx, – Satys

+0

對不起,延遲,我只是設置它,我現在就試試吧! – Acidic

6

Nginx的免費解決方案的機器的IP。

首先,你可以重定向connections on port 80 as a normal user

sudo apt-get install iptables-persistent 
sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8000 
sudo netfilter-persistent save 
sudo netfilter-persistent reload 

然後使用gorilla/mux或類似建立一個路由,每個主機,甚至從它

r := mux.NewRouter() 
s := r.Host("www.example.com").Subrouter() 

因此,完整的解決方案獲得了「subrouter」將是

package main 

import (
    "net/http" 
    "github.com/gorilla/mux" 
    "fmt" 
) 

func Example1IndexHandler(w http.ResponseWriter, r *http.Request) { 
    fmt.Fprintf(w, "Hello www.example1.com!") // send data to client side 
} 

func Example2IndexHandler(w http.ResponseWriter, r *http.Request) { 
    fmt.Fprintf(w, "Hello www.example2.com!") // send data to client side 
} 

func main() { 
    r := mux.NewRouter() 
    s1 := r.Host("www.example1.com").Subrouter() 
    s2 := r.Host("www.example2.com").Subrouter() 

    s1.HandleFunc("/", Example1IndexHandler) 
    s2.HandleFunc("/", Example2IndexHandler) 

    http.ListenAndServe(":8000", nil) 
} 
+0

我看到這可能會如何工作,但有幾個網站來主辦,這種方法可能有點混亂。 – Acidic

+0

這完全取決於建築設計。以[microservices](https://en.wikipedia.org/wiki/Microservices)爲例。我不說反向代理是一個壞主意,只是需要考慮更多的選擇。 –

相關問題