I'm trying to do a custom dockerfile with jenkins on it. I would to wait until port 8080 is open instead of doing an ugly 'sleep 60' with netcat but in not very confident with bash scripts and netcat.
Here is an example of what i'm trying to do:
#!/bin/bash
opened=0
while [ "$opened" == "0" ]; do
echo "Waiting jenkins to launch on 8080..."
nc -vz localhost 8080
done
echo "Jenkins launched"
As suggested here, you could also do the following if you don't have
nc
installed but justbash
andcoreutils
:You can't set netcat to wait until some port is open, so you have to add part for waiting before next check is made. Try this:
I suggest the following one liners:
Both commands exit as soon as connection is established, trying every second for up to 22 seconds.
Note that thanks to
timeout
command exit code is0
when port is accessible otherwise124
(if no connection established within given time).I have found this a common enough problem to write a utility to wait for a port to open, with an optional timeout:
It's open source and available at github.com/dwmkerr/wait-port. Hopefully others will find it useful!
To expand on user987339's answer, here's how to easily wait for a port in your terminal:
waitport function
Add this function to your ~/.bashrc setup file:
Log out then back in to load ~/.bashrc. Then, run this command to verify that port 3000 has a server listening to it:
This has been validated on macOS. It might not work on Fedora/CentOS, as they lack the
-z
option fornetcat
.