2

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?

Johnney
  • 161
  • 1
  • 9
  • Can you please try `mybridge`'s ip address on your system (you can find it with `ip a s` in linux) and port 4222? Also, I think it would be better to create docker-compose for this. – Parham Alvani Nov 12 '22 at 01:30
  • My problem is twofold: first, I am trying to do this part on a Windows Machine. Second, after docker container working, I am going to be using the image in kubernetes. – Johnney Nov 12 '22 at 15:01
  • In the kubernetes part I think you shouldn't have any issue because your networking there is based on services. On the windows machine I think you can get the ip address with `ipconfig`. – Parham Alvani Nov 12 '22 at 15:57
  • 1
    It ends up working when I shift from a Windows-based Machine to a Linux based one – Johnney Nov 12 '22 at 22:27

0 Answers0