Luk*_*lly 6 networking go docker ubuntu-20.04
我正在尝试在 docker 容器内运行用 Golang 编写的 HTTP 服务器,但连接不断被拒绝。一切都在我的 Windows 10 计算机上运行的 Ubuntu 20.04 Server VM 内运行。
Go服务器代码:
package main
import "github.com/lkelly93/scheduler/internal/server"
func main() {
    server := server.NewHTTPServer()
    server.Start(3000)
}
package server
import (
    "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.04
RUN apt-get update -y
#Install needed packages
RUN apt-get install software-properties-common -y
RUN apt-get install python3 -y
RUN apt-get update -y 
RUN apt-get install python3-pip -y
RUN 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 DIRs
RUN mkdir secure
RUN mkdir secure/runner_files
COPY scheduler /secure
WORKDIR /secure
EXPOSE 3000
CMD ["./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 机器调用它没有问题,但当它存在于 Ubuntu 机器的 docker 容器内时,我似乎无法调用 Go 服务器。
Go 代码比这更复杂,但在这里发布所有内容实在太多了,请随意查看整个存储库:https://github.com/lkelly93/scheduler。
最终它将成为我想要运行代码的网站的后端。类似于 LeetCode 或 Repl.it。
谢谢!
编辑:
docker container ls -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS                    NAMES
2a56a973040f        scheduler:latest    "./scheduler"       37 seconds ago      Up 36 seconds       0.0.0.0:3000->3000/tcp   scheduler
docker 容器日志 2a56a973040f 没有给出任何输出。
编辑2:
docker run -it --net container:2a56a973040f nicolaka/netshoot ss -lnt
State  Recv-Q Send-Q Local Address:Port Peer Address:PortProcess
LISTEN 0      4096               *:3000            *:*
编辑3:
阅读手册页后,我发现如果我的图像带有标签 --network=host 然后运行。
curl http://localhost:3000/execute/python --data '{"Code":"print(\"Hello\")"}'
我得到了正确的输出。虽然这有效,但我希望有多个并排运行的 Docker 映像。所以我更愿意使用 IP 地址来解决所有问题。所以我不认为这是一个永久的解决办法。
为了在我的服务器上解决这个问题,我将 IP 地址设置为 0.0.0.0:4000。我正在使用杜松子酒,所以这个例子看起来像:
r := gin.Default()
r.run("0.0.0.0:4000")
之后我终于可以通过浏览器访问它了。
| 归档时间: | 
 | 
| 查看次数: | 2956 次 | 
| 最近记录: |