Monday 11 April 2022

Sending UDP packets from docker container to localhost

It has been a long while since my last post, and now instead of a proper post, just a trivial note on the issue I had. Yet it might be the one saving hours for you out there, the hours I wasted yesterday trying so many different combinations just to find out what was trying to do was impossible.

So what is impossible?

Sending UDP packets (and more generally: just communicating) from a docker container to a listener running on the localhost is impossible.

What... surely this is a joke?!

This is no joke. I was running a UDP listener for a tiny project I was working on and it was hosted on port 1969 (arguably the best port number, after the best year in rock music) with "localhost" as the host name (rather the IP listening on). I needed to generate a lot of data being sent and I created a little docker container to send lots of UDP packets.

I changed the IP to surely will help? Nope.

Then I stumbled on this which essentially suggesting using network mode of "host" is needed to do the trick. That too to no avail.

It made me doubt my solution so I resorted to landing on the bash of the container and trying with netcat. When the error persisted I realised I am dealing with an impossible scenario.

The solution

Well the solution in the end in my case was this: just give up, do not send to localhost - instead send to host.docker.internal

This might be a particularity of MacOS implementation of the docker that you cannot reach the host (the other posts were suggesting the could reach localhost) but all in all, for your scenarios in order for the container to reach the host networking, just use that. This has been mapped to on Mac and Windows implementation of the docker seems to use the same IP.

That is it.

I hope someone might find this useful.