How do you dockerize a WebSocket Server?

后端 未结 1 1426
清歌不尽
清歌不尽 2020-12-14 13:05

I\'m having trouble with putting my WebSocket server in a Docker container.

This is the server code, which writes to a new connection with \"connected\".

<         


        
相关标签:
1条回答
  • 2020-12-14 13:31

    When you specify a hostname or IP address​ to listen on (in this case localhost which resolves to 127.0.0.1), then your server will only listen on that IP address.

    Listening on localhost isn't a problem when you are outside of a Docker container. If your server only listens on 127.0.0.1:8000, then your client can easily connect to it since the connection is also made from 127.0.0.1.

    When you run your server inside a Docker container, it'll only listen on 127.0.0.1:8000 as before. The 127.0.0.1 is a local loopback address and it not accessible outside the container.

    When you fire up the docker container with -p 8000:8000, it'll forward traffic heading to 127.0.0.1:8000 to the container's IP address, which in my case is 172.17.0.2.

    The container gets an IP addresses within the docker0 network interface (which you can see with the ip addr ls command)

    So, when your traffic gets forwarded to the container on 172.17.0.2:8000, there's nothing listening there and the connection attempt fails.

    The fix:

    The problem is with the listen address:

    server := http.Server{Addr: "localhost:8000"}
    

    To fix your problem, change it to

    server := http.Server{Addr: ":8000"}
    

    That'll make your server listen on all it container's IP addresses.

    Additional info:

    When you expose ports in a Docker container, Docker will create iptables rules to do the actual forwarding. See this. You can view these rules with:

    iptables -n -L 
    iptables -t nat -n -L
    
    0 讨论(0)
提交回复
热议问题