Reputation: 11
I have got a Go and Elasticsearch task and I see an error that I don't understand. Normally, my code works without Docker.
This is my compose.yml
version: '3.1'
services:
elasticsearch:
image: docker.elastic.co/elasticsearch/elasticsearch:7.15.0
container_name: elasticsearch
ports:
- 9201:9200
environment:
- discovery.type=single-node
monolith:
build:
context: .
ports:
- 3001:3001
depends_on:
- elasticsearch
Dockerfile
:
FROM golang:1.22 AS build-env
WORKDIR /src
ENV CGO_ENABLED=0
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN go build -a -o webpalm -trimpath
FROM scratch AS final
WORKDIR /
COPY --from=build-env /src/webpalm .
COPY --from=build-env /src/sample.json .
CMD ["./webpalm"]
My Go code:
for _, item := range items {
req := esapi.IndexRequest{
Index: "sample_index",
DocumentID: item.ID,
Body: bytes.NewReader(encodeJSON(item)),
Refresh: "true",
}
res, err := req.Do(context.Background(), es)
if err != nil {
fmt.Println("Data indexing error", err)
return
}
defer res.Body.Close()
}
Upvotes: 0
Views: 389
Reputation: 1937
The issue here is that your Elasticsearch and your Go application don't share the localhost
network. Instead, connect to Elasticsearch using the service name defined in docker-compose.yml
. Change your Go application's Elasticsearch connection string from 127.0.0.1:9200
to elasticsearch:9200
.
With this modification, your Go application would communicate with Elasticsearch through Docker's internal networking, using the service name as the hostname.
Upvotes: 0