For a project I have a Go Server running in a Docker container, a NATs Server, and a standalone client. The server tries to send messages through NATs. To connect to NATs, it uses the following code:
var nc, err = nats.Connect(nats.DefaultURL)
if err != nil {
panic(err)
}
defer nc.Close()
But when I try to run the server, I get an error which causes the program and container to stop: panic: nats: no servers available for connection
. This seems to mean that the program Server in the container cannot find the NATs that is running.
Both Windows-server and NATs are running in the same Docker Network.
And when I enter into the Container and use telnet to access Nats at the port nats:4222, telnet finds the NATs server correctly
/app # busybox-extras telnet nats:4222
Connected to nats:4222
INFO {"server_id":"NBFTCFLMIEXINXIRG5LSJ2MGT4J574OYHHJ7AANWDTWQERKZ76LG7RVQ","server_name":"NBFTCFLMIEXINXIRG5LSJ2MGT4J574OYHHJ7AANWDTWQERKZ76LG7RVQ","version":"2.9.6","proto":1,"git_commit":"289a9e1","go":"go1.19.3","host":"0.0.0.0","port":4222,"headers":true,"max_payload":1048576,"client_id":12,"client_ip":"172.20.0.3","cluster":"my_cluster"}
I have already tried to change the URL that nats.Connect
is connecting to, and none of them have worked. I have tried "nats"
and "nats:4222"
and "nats://nats:4222"
, and the NATs URLs as well. I do not know what I am doing incorrectly.
The Dockerfile of the Container looks like this:
FROM golang:alpine
WORKDIR /app
COPY . .
RUN apk update
RUN apk add ffmpeg libsm libxext
RUN go mod download
RUN go build -o server
EXPOSE 50051
CMD ["./server"]
I set up NATs with the command docker run -d --rm --name nats --network=mybridge -p 4222:4222 nats
, the server with docker run -d --name windows-server --network=mybridge -p 50051:50051 windows-server
The Server works correctly when it is running outside of a container. How do I make the program access NATs from within a container?