unable to reach docker container macos code example

Example: mac container endpoint not working

Another challenge was actually connecting to my API endpoint running in my container from my local machine. Prior to using Docker, I had been specifying a particular IP address for my localhost when setting up http.ListenAndServe, e.g. http.ListenAndServe(“127.0.0.1:8080”, nil), but seeing as when you run your container using Docker for Mac, you’re running within a lightweight VM, it will have a different IP than the standard loopback localhost IP (127.0.0.1). I tried docker inspect but had a pretty hard time figuring out exactly what IP I would need to try and hit to make this work. I ended up removing the loopback localhost IP from the addr function parameter for http.ListenAndServe and only have the port as part of the string, as in below (“:8080”).

// ListenAndServe on port 8080, not specifying a particular IP address for this particular implementation
if err := http.ListenAndServe(":8080", nil); err != nil {
    log.Fatal(err)
}

//using golang fiber 2.0. Dont specifiy the localhost or ip and only provide port number to listen
func main() {
	app := fiber.New()
	app.Listen(":3001")
}
Once you’ve removed this IP, you can then use “localhost” and port 8080 to connect to your APIs running within the container. Requests will be properly forwarded

Tags:

Misc Example