我正在嘗試在 docker 容器內運行一個用 Golang 編寫的 HTTP 服務器,但我一直被拒絕連接。一切都在我的 Windows 10 機器上運行的 Ubuntu 20.04 Server VM 內運行。Go 服務器代碼:package mainimport "github.com/lkelly93/scheduler/internal/server"func main() { server := server.NewHTTPServer() server.Start(3000)}package serverimport ( "context" "fmt" "net/http")type HTTPServer interface { Start(port int) error Stop() error}func NewHTTPServer() HTTPServer { return &httpServer{}}type httpServer struct { server *http.Server}func (server *httpServer) Start(port int) error { serveMux := newServeMux() server.server = &http.Server { Addr: fmt.Sprintf(":%d", port), Handler: serveMux, } return server.server.ListenAndServe()}func (server *httpServer) Stop() error { return server.server.Shutdown(context.Background())}我的 Dockerfile:FROM ubuntu:20.04RUN apt-get update -y#Install needed packagesRUN apt-get install software-properties-common -yRUN apt-get install python3 -yRUN apt-get update -y RUN apt-get install python3-pip -yRUN apt-get install default-jre -y#Install language dependacies #Python RUN pip3 install numpy#Reduce VM size# RUN rm -rf /var/lib/apt/lists/*#Setup working DIRsRUN mkdir secureRUN mkdir secure/runner_filesCOPY scheduler /secureWORKDIR /secureEXPOSE 3000CMD ["./scheduler"] <-- The go server is compiled into a binary called scheduler我構建給定的 Dockerfile,然后運行:docker run -d --name scheduler -p 3000:3000 scheduler:latest然后我抓住容器的地址:docker inspect --format='{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' scheduler->172.17.0.2最后我使用 cURL 發送一個 http 請求:curl http://172.17.0.2:3000/execute/python --data '{"Code":"print(\"Hello\")"}'我正進入(狀態curl: (7) Failed to connect to 172.17.0.2 port 3000: Connection refused但應該得到{"Stdout":"Hello\n"}%如果我在 Ubuntu VM 上運行 Go 服務器,從我的 Win10 機器調用它沒有問題,但是當 Go 服務器存在于 Ubuntu 機器的 docker 容器中時,我似乎無法調用它。Go 代碼比這更復雜,但是在這里發布所有內容太多了,請隨時查看https://github.com/lkelly93/scheduler上的整個 repo 。最終它將成為我想要運行代碼的網站的后端。像 LeetCode 或 Repl.it 這樣的東西。
3 回答

LEATH
TA貢獻1936條經驗 獲得超7個贊
為了在我的服務器上解決這個問題,我將 IP 地址設置為 0.0.0.0:4000。我正在使用杜松子酒,所以這個例子看起來像:
r := gin.Default() r.run("0.0.0.0:4000")
在此之后,我終于能夠通過我的瀏覽器訪問它。

叮當貓咪
TA貢獻1776條經驗 獲得超12個贊
您已經發布了端口,它將端口從 docker 主機轉發到容器。因此,您要連接到 http://localhost:3000。桌面安裝時連接到容器 IP 可能會失敗,因為 docker 在 VM 內部運行,并且這些私有 IP 僅在 VM 中可見。
如果您碰巧正在運行docker-machine
(安裝較舊的 docker 工具箱就是這種情況),那么您需要獲取 VM 的 IP。運行echo $DOCKER_HOST
查看IP地址并將端口調整為3000端口。

慕的地6264312
TA貢獻1817條經驗 獲得超6個贊
- 3 回答
- 0 關注
- 161 瀏覽
添加回答
舉報
0/150
提交
取消