Skip to content
Latchkey

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

Terminal
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 5432

Options

FlagWhat it does
-zZero-I/O mode: scan for a listener, send no data
-vVerbose: print "open" or "Connection refused"
-w <secs>Timeout for the connection attempt
-uUse UDP instead of TCP
-nSkip 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.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →