Reputation: 157
Trying to create a Docker container for my Go application - it creates a HTTP server on port 8080:
package main
import (
"net/http"
)
func main() {
http.HandleFunc("/", doX)
if err := http.ListenAndServe("localhost:8080", nil); err != nil {
panic(err)
}
}
func doX(w http.ResponseWriter, r *http.Request) {
x
}
When I run go build and then go to localhost:8080 it works, however it's unresponsive when I try building and running it in Docker:
# Start from the latest golang base image
FROM golang:1.14.3-alpine
# Set the Current Working Directory inside the container
WORKDIR /app
# Copy the source from the current directory to the Working Directory inside the container
COPY /src .
# Build the Go app
RUN go build -o main .
# Expose port 8080 to the outside world
EXPOSE 8080
# Command to run the executable
CMD ["./main"]
The commands I'm running are:
docker build -t src . docker run -d -p 8080:8080 src
All my .go files are in a directory called 'src'. Help appreciated - quite new to Docker, thanks!
Upvotes: 3
Views: 1714
Reputation: 63
change the host from localhost to 0.0.0.0
. It will be fine.
i.e
func main() {
http.HandleFunc("/", doX)
if err := http.ListenAndServe("0.0.0.0:8080", nil); err != nil {
panic(err)
}
}
The main idea of loopback is serving resources on SAME HOST. if you are exposing a port, the host changes so it should throw a connection reset by peer
kind of error.
Alternatively, you may wish to create a network if your golang application needs to communicate between other containers of different images. So first a new network needs to be created.
docker network create <network_name>
Then while booting this go container along with different containers(if at all required) pass the network
flag to make them available under the same subnet.
docker run --network <network_name> -d -p 8080:8080 src
If you don't want to do that run the container on host
network of docker (PS. it's not the standard practice, but good for debugging). If you have run your src image in the host
network with localhost
at http.ListenAndServe
, you could instantly notice that it is accessible but while exposing the port on docker's bridge
network mode, it's not accessible. So there must be some error in the application setup where it is invisible to the outside network.
docker run -d --network host src
Thanks :)
Upvotes: 5