How to add a docker health check to test a tcp port is open?

Viewed 10870

I have a server which is running an apache hive service on port 9083. The thing is it doesn't support http protocol (but uses thrift protocol).so I can't simply add

HEALTHCHECK CMD http://127.0.0.1:9083 || exit 1 #  this check fails

All I want is to check if that port is open. I have netstat and curl on server but not nc.

So far I tried the below options, but none of them is suitable as a health check.

netstat -an | grep 9083 | grep LISTEN | echo $?  # This works
netstat -an | grep 9084 | grep LISTEN | echo $? # but so does this

The problem as I interpret from the above is it's simply telling me my syntax is correct, but not really testing if that port is really listening

because when I do netstat -an I get the following output,which clearly shows only 9083 is listening but not 9084

Active Internet connections (servers and established) Proto Recv-Q Send-Q Local  Address           Foreign Address         State tcp       0      0 
 0.0.0.0:9083            0.0.0.0:*               LISTEN tcp    0      0 
4 Answers

The shorter version of it:

netstat -ltn | grep -c 9083

Used options:

netstat:

  • -l - display listening server sockets
  • -t - display TCP sockets only
  • -n - don't resolve names

grep

  • -c - returns a number of founded lines, but it also gives a useful exit code; 0 if found, 1 if not found

Piotr Perzynas answer is quite good, but it will also return 0 if there‘s a port like 19083 because it finds the substring 9083 in that line. a better check would be:

netstat -ltn | grep -c ":9083"
Related