dial tcp 127.0.0.1:8000: connect: connection refused golang docker containers

Issue

I am trying to make an http request from one project to another both using GO. The project that is making the request has the following dockerfile:

FROM golang:alpine as builder
WORKDIR /build
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -ldflags '-extldflags "-static"' -o main .
FROM scratch
WORKDIR /app
COPY --from=builder /build .
CMD ["./main"]

The project that is waiting for the request is running on localhost:8000 and it has the following dockerfile:

FROM golang:1.13.8 AS build-env
ADD . /dockerdev
WORKDIR /dockerdev
RUN go get -d -v ./...
RUN go build -o /server
# Final stage
FROM debian:buster
EXPOSE 8000
WORKDIR /
COPY --from=build-env /server /
CMD ["/server"]

When I make

resp, err := http.Post("http://localhost:8000/orders", "application/json", bytes.NewBuffer(requestBody))

it gives me the following error

dial tcp 127.0.0.1:8000: connect: connection refused

I am new to docker so any improvements are welcome!

Solution

Expanding on my comment. Your client code’s network address will not work:

resp, err := http.Post("http://localhost:8000/orders", "application/json", bytes.NewBuffer(requestBody)) // broken

as it is literally talking to itself (localhost refer to the client docker container – not the host OS).


The quickest way – for testing purposes – to expose the two containers to your host OS would be like so:

docker run -it --rm -p 8000:8000 dockweb  # server container
docker run -it --rm --net host dockcli    # client container

Beyond trivial testing, this can quickly get unwieldy. So I recommend using things like docker-compose which allows you to trivially link containers and their networks.

Answered By – colm.anseo

Answer Checked By – Marilyn (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.