Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go server empty response in Docker container

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.

like image 603
The Exile Avatar asked Apr 25 '26 05:04

The Exile


1 Answers

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
like image 172
colm.anseo Avatar answered Apr 28 '26 04:04

colm.anseo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!