DevNotes

Concise, Handy and Elegant Notes for Developers

0%

Host <--> Docker

A recent project, we have to send TCP and UDP data from Host to Docker, back and forth. Docker is great and it is easy to expose port to provide service inside Docker instance. For example:

1
docker run -itd --name my_instance -p 1111:2222 -p 8888:9999/udp my_image

Here we map the TCP port 1111 from host to 2222 inside docker instance, and UDP port 8888 on host to 9999 in docker, and some help commands we use frequently such as

Now we come to the TCP/UDP communication testing. Basically the command netcat/nc is good enough for make data coming through.

1
2
3
4
5
6
7
# TCP
nc -l 1234
echo "hi" | nc localhost 1234

# UDP
nc -ul 1234
echo "hi" | nc -4u localhost 1234

Normally this two pairs work perfectly for most testing purpse, just be careful for the port forwarding of docker. However there is an issue for macOS, and there is a workaround suggested by Docker offical sites. In short, use the command below to attach an unused IP to lo0 interface

1
2
3
4
5
6
7
8
sudo ifconfig lo0 alias 192.168.0.111/24

# In case you want to realse the attach
sudo ifconfig lo0 -alias 192.168.0.111

# Two more useful command for check ports listening when debugging
netstat -lna | grep udp
lsof -i4 -P -a -n