nc -z: Check If a Port Is Open in CI
nc -z opens a connection to a host:port, reports whether it succeeded, and exits without transferring data.
When a CI step needs to know if a database or API is reachable, nc -z is the quickest probe. It returns a clean exit code you can branch on.
What it does
nc -z (zero-I/O mode) attempts a connection to the target port and immediately closes it, printing success or nothing depending on -v. Exit status is 0 if the port accepted the connection and non-zero otherwise, which makes it ideal for scripted checks.
Common usage
nc -z localhost 5432 && echo "Postgres is up"
nc -zv db.internal 5432
# bound the attempt so a firewalled host does not hang the job
nc -z -w 5 db.internal 5432Options
| Flag | What it does |
|---|---|
| -z | Zero-I/O mode: scan for a listener, send no data |
| -v | Verbose: print "open" or "Connection refused" |
| -w <secs> | Timeout for the connection attempt |
| -u | Use UDP instead of TCP |
| -n | Skip DNS resolution, treat the host as a literal IP |
In CI
Pair -z with -w so a dropped or filtered port fails fast instead of hanging until the job timeout. Without -w the OpenBSD nc waits on the kernel default, which can be minutes on a SYN that is silently dropped by a firewall.
Common errors in CI
"nc: connect to host port 5432 (tcp) failed: Connection refused" means nothing is listening yet, common when a service container has not finished starting. "Connection timed out" means a firewall is dropping packets, not refusing them. "nc: invalid option -- 'z'" means the busybox nc on alpine, which lacks -z; use -w 1 with </dev/null or install netcat-openbsd.