Reputation: 704
I have a Go server which something like that. Router is Gorilla MUX
var port string
if port = os.Getenv("PORT"); port == "" {
port = "3000"
}
srv := &http.Server{
Handler: router,
Addr: "localhost:" + port,
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
fmt.Println("Server is running on port " + port)
log.Fatal(srv.ListenAndServe())
Dockerfile is
# Build Go Server
FROM golang:1.14 AS go-build
WORKDIR /app/server
COPY cmd/ ./cmd
COPY internal/ ./internal
COPY go.mod ./
COPY go.sum ./
RUN go build ./cmd/main.go
CMD ["./main"]
I got successful a build. I ran it with following command
docker run -p 3000:3000 baaf0159d0cd
And I got following output. Server is running
Server is running on port 3000
But when I tried to send request with curl I got empty response
>curl localhost:3000
curl: (52) Empty reply from server
Why is server not responding properly? I have another routes which I did not put here and they are not responding correctly too. I am on MacOS by the way.
Upvotes: 9
Views: 3963
Reputation: 22087
Don't use localhost
(basically an alias to 127.0.0.1
) as your server address within a Docker container. If you do this only 'localhost' (i.e. any service within the Docker container's network) can reach it.
Drop the hostname to ensure it can be accessed outside the container:
// Addr: "localhost:" + port, // unreachable outside container
Addr: ":" + port, // i.e. ":3000" - is accessible outside the container
Upvotes: 11