Checking API status using netstat/ss

But, how do we know when the API is ready? We could send a request to one of the API's endpoints and see if it returns a result. However, this couples our script with the implementation of the API. A better way would be to check whether the API is actively listening to the server port. We can do this using the netstat utility, or its replacement, ss (which stands for socket statistics). Both commands are used to display network-related information such as open connections and socket ports:

$ netstat -lnt
$ ss -lnt

For both commands, the -l flag will limit the results to only listening sockets, the -n flag will display all hosts and ports as numeric values (for instance, it'll output 127.0.0.1:631 instead of 127.0.0.1:ipp), and the -t flag will filter out non-TCP sockets. The end result is an output that looks like this:

$ netstat -lnt
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 127.0.0.1:5939 0.0.0.0:* LISTEN
tcp 0 0 127.0.0.1:53 0.0.0.0:* LISTEN
tcp6 0 0 ::1:631 :::* LISTEN
tcp6 0 0 :::8888 :::* LISTEN
tcp6 0 0 :::3128 :::* LISTEN

To check whether a specific port is listening, we can simply run grep on the output (for instance, ss -lnt | grep -q 8888) If grep finds a result, it will exit with a status code of 0; if no matches are found, it will exit with a non-zero code. We can use this feature of grep to poll ss at regular intervals until the port is bound.

Add the following block below our yarn run serve & command:

RETRY_INTERVAL=0.2
until ss -lnt | grep -q :$SERVER_PORT; do
sleep $RETRY_INTERVAL
done