Website Vidya
Web ServerStep-by-Step Guide

nslookup Command in Linux: Query DNS Records and Name Servers

Learn nslookup command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

RR
Rajesh RayLead Systems Educator
Published:
11 min read
PDF Cheat Sheet
nslookup Command in Linux: Query DNS Records and Name Servers
AI Executive SummaryWebsiteVidya AI

11 min read

Learn nslookup command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

Key Highlights
  • What nslookup Does and When to Use It
  • Availability and Installation Across Linux Distributions
  • Command Syntax, Arguments, and Exit Status Codes
Grounded in full engineering runbookWebsiteVidya AI Engine

Mastering the nslookup command in linux provides system administrators, site reliability engineers, and network professionals with a dependable, cross-platform diagnostic utility for querying Domain Name System (DNS) servers. Originally authored as part of the BIND (Berkeley Internet Name Domain) software suite, nslookup translates human-readable hostnames into numeric IPv4 and IPv6 addresses, interrogates authoritative nameservers, and diagnoses delegation and propagation anomalies across distributed networks.

DNS resolution is foundational to modern networked infrastructure, serving as the distributed database that powers web hosting, mail routing, TLS certificate verification, and cloud microservice discovery. When application services report connection timeouts, mail relays fail to route messages, or newly published DNS changes fail to propagate, nslookup allows engineers to isolate whether the failure stems from a local resolver cache, an upstream recursive DNS forwarder, or an authoritative nameserver configuration error.

Although early BIND 9 releases briefly marked nslookup as deprecated in favor of dig and host, the Internet Systems Consortium (ISC) completely rewrote nslookup atop modern BIND shared libraries (libdns). Today, nslookup remains fully supported, actively maintained, and universally installed across Linux distributions, BSD variants, and Windows environments, making it a critical tool for portable, multi-platform DNS administration.

Advertisement
nslookup Command in Linux: Query DNS Records and Name Servers — syntax, flags, and practical terminal workflow diagram
nslookup Command in Linux: Query DNS Records and Name Servers — command syntax, key options, and production workflow reference.

What nslookup Does and When to Use It

At the architectural level, nslookup communicates with DNS servers using standard RFC 1035 UDP and TCP packets directed to port 53. By default, queries are dispatched as single UDP datagrams. If a response exceeds 512 bytes (or the negotiated EDNS0 buffer size), the DNS server sets the Truncated (TC) bit in the header, prompting nslookup to automatically retry the transaction over a stateful TCP connection using the virtual circuit (vc) mechanism.

Unlike standard system utilities that rely on the C library getaddrinfo(3) or gethostbyname(3) wrappers—which consult the Name Service Switch configuration in /etc/nsswitch.conf and local hosts tables in /etc/hosts—nslookup acts as an independent DNS stub client. It parses /etc/resolv.conf solely to identify configured nameserver IP addresses, search domains, and query timeout parameters, sending raw DNS wire-format queries directly over network sockets.

At the operating system level, nslookup interacts with the Linux kernel networking stack through netlink sockets (AF_NETLINK), raw packet sockets, or standard POSIX resolver APIs. When running nslookup in cloud instances or Kubernetes worker nodes, combining flags such as -type=TYPE, -timeout=N, -retry=N, -port=N lets you bypass slow reverse DNS lookups and inspect numeric IPv4/IPv6 addresses and socket states directly.

Availability and Installation Across Linux Distributions

The nslookup utility is packaged in bind-utils across mainstream Linux distributions. It is pre-installed on standard Ubuntu, Debian, RHEL, Rocky Linux, AlmaLinux, Fedora, and Arch Linux systems, while minimal container images may require manual installation:

Advertisement

Before running administrative tasks or automation scripts, verify whether nslookup is installed and inspect which binary path and version your shell resolves:

type -a nslookup
nslookup --version 2>/dev/null || man -f nslookup

# Illustrative output (reviewed against documentation)
nslookup is /usr/bin/nslookup
nslookup (bind-utils)
# Debian / Ubuntu
sudo apt-get update && sudo apt-get install -y dnsutils

# RHEL / Rocky / AlmaLinux / Fedora
sudo dnf install -y bind-utils

# Arch Linux
sudo pacman -S --noconfirm bind

# Alpine Linux
sudo apk add --no-cache bind-tools

Command Syntax, Arguments, and Exit Status Codes

nslookup [-option] [hostname | ip] [server]

The command operates in two distinct execution modes: non-interactive mode and interactive mode. In non-interactive mode, you invoke nslookup followed by optional flags, the target domain or IP address, and an optional custom DNS server (for example, nslookup -type=MX example.com 8.8.8.8). This mode executes a single query, prints the formatted response to standard output, and exits immediately, making it ideal for command-line one-liners and shell scripts.

In interactive mode, invoked by typing nslookup without any domain arguments, the utility presents an interactive prompt (>). From within this prompt, administrators can dynamically change resource record types using set type=RECORD, toggle debugging with set debug, redirect queries to different nameservers using the server command, and inspect zone transfers using ls. Type exit or press Ctrl+D to terminate the interactive session.

  • 0 — The requested DNS query completed successfully and returned valid resource records.
  • 1 — The DNS server returned an error (such as NXDOMAIN or SERVFAIL), the query timed out, or no answering nameservers could be reached.
  • 2 — Invalid command-line arguments, malformed option syntax, or internal resolver initialization failure.

Important Options and Flags Reference

Option / FlagLong Form / ArgumentTechnical Behavior and Purpose
-type=TYPE-query=TYPESpecifies the DNS resource record type to query (e.g., A, AAAA, MX, NS, SOA, TXT, CNAME, PTR, or ANY).
-timeout=N-timeout=NSets the initial query response timeout interval to N seconds before retransmitting the query.
-retry=N-retry=NSpecifies the number of times to retransmit a query packet before declaring the DNS server unreachable.
-port=N-port=NOverrides the default UDP/TCP destination port (53) to query DNS servers listening on custom ports.
-debug-debugEnables verbose debugging output, showing packet headers, question sections, authority records, and TTL values.
-nodebug-nodebugSuppresses detailed packet debugging output (default behavior).
-recurse-recurseRequests recursive resolution from the queried nameserver by setting the RD (Recursion Desired) bit in query headers.
-norecurse-norecurseClears the RD bit, instructing the queried nameserver to return only iterative referrals or local authoritative data.
-vc-vcForces the query to use a stateful TCP connection (virtual circuit) instead of default UDP datagrams.

When diagnosing DNS issues, combining the -type= flag with an explicit nameserver argument is the most effective way to eliminate intermediary caching. For example, pointing nslookup -type=SOA example.com ns1.example.com directly at the authoritative primary server reveals the canonical serial number, bypassing any stale Time-To-Live (TTL) records cached by local ISPs or corporate resolvers.

Advertisement

For deep protocol troubleshooting, pairing -debug with -vc forces TCP transmission and displays the raw transaction ID, response flags (such as Authoritative Answer aa and Recursion Available ra), and precise TTL countdown values for every record in the answer and authority sections.

When combining short flags on the command line, POSIX and GNU utilities allow clustering boolean flags behind a single hyphen, provided any option taking an argument appears last. In automated shell scripts, using long-form GNU options where portable makes self-documenting code that is easier to audit during peer review.

Practical Basic and Advanced Usage Examples

1. Query Basic IPv4 Address (A Record) for a Domain

Perform a standard non-interactive forward DNS lookup to resolve the IPv4 addresses associated with a domain name using the default system resolver.

nslookup example.com

# Illustrative output (reviewed against documentation)
Server:         127.0.0.53
Address:        127.0.0.53#53

Non-authoritative answer:
Name:   example.com
Address: 93.184.216.34

The output identifies the querying resolver (127.0.0.53, systemd-resolved), denotes that the answer was retrieved from cache (Non-authoritative), and displays the resulting IPv4 address.

2. Query a Specific Public DNS Server Directly

Bypass local caching resolvers and query a specific public nameserver (such as Cloudflare 1.1.1.1 or Google 8.8.8.8) to verify external DNS propagation.

nslookup example.com 1.1.1.1

# Illustrative output (reviewed against documentation)
Server:         1.1.1.1
Address:        1.1.1.1#53

Non-authoritative answer:
Name:   example.com
Address: 93.184.216.34

Appending 1.1.1.1 forces nslookup to direct the UDP query packet directly to Cloudflare's public resolver, confirming external name resolution.

3. Query Mail Exchange (MX) Records for Email Routing

Retrieve the mail exchange servers responsible for accepting incoming email for a domain, including priority weighting values.

nslookup -type=MX example.com

# Illustrative output (reviewed against documentation)
Server:         127.0.0.53
Address:        127.0.0.53#53

Non-authoritative answer:
example.com     mail exchanger = 10 mail.example.com.

The -type=MX flag instructs the resolver to fetch MX resource records. The output indicates that mail.example.com handles mail with preference priority 10.

4. Inspect TXT Records for SPF, DKIM, and Verification Tokens

Query domain TXT records to validate Sender Policy Framework (SPF) email authentication policies, domain ownership strings, and DMARC configurations.

nslookup -type=TXT example.com

# Illustrative output (reviewed against documentation)
Server:         127.0.0.53
Address:        127.0.0.53#53

Non-authoritative answer:
example.com     text = "v=spf1 -all"
example.com     text = "google-site-verification=rXOxyZounnZasA8Z707aepQegP8GAD9uvQ00GJRoll0"

The query returns all published TXT strings, allowing administrators to audit SPF mechanisms and domain verification hashes.

5. Perform a Reverse DNS Lookup (PTR Record)

Resolve an IP address back to its fully qualified domain name (FQDN) using the special in-addr.arpa reverse DNS namespace.

nslookup 93.184.216.34

# Illustrative output (reviewed against documentation)
Server:         127.0.0.53
Address:        127.0.0.53#53

Non-authoritative answer:
34.216.184.93.in-addr.arpa      name = 93.184.216.34.

Supplying an IP address causes nslookup to automatically construct the dotted-quad in-addr.arpa PTR query and display the associated canonical hostname.

6. Inspect Start of Authority (SOA) Records and Zone Serial Numbers

Retrieve the Start of Authority record to verify primary nameserver identity, administrative contact, and zone file serial number.

nslookup -type=SOA example.com

# Illustrative output (reviewed against documentation)
Server:         127.0.0.53
Address:        127.0.0.53#53

Non-authoritative answer:
example.com
        origin = sns.dns.icann.org
        mail addr = noc.dns.icann.org
        serial = 2026102101
        refresh = 7200
        retry = 3600
        expire = 1209600
        minimum = 3600

The SOA record provides critical zone transfer parameters: primary origin server, contact email (with @ replaced by dot), serial number, refresh intervals, and negative caching TTL.

Real-World Workflows, Pipelines, and Shell Automation

Automated Multi-Resolver DNS Propagation Verification Script

When deploying DNS record modifications (such as updating web server IP addresses or migrating mail services), verify global propagation across major public resolvers before cutting over production traffic.

#!/usr/bin/env bash
set -euo pipefail

DOMAIN="example.com"
EXPECTED_IP="93.184.216.34"

RESOLVERS=(
  "1.1.1.1#Cloudflare"
  "8.8.8.8#Google"
  "9.9.9.9#Quad9"
  "208.67.222.222#OpenDNS"
)

echo "=== Verifying DNS Propagation for: ${DOMAIN} ==="
for item in "${RESOLVERS[@]}"; do
  SERVER="${item%%#*}"
  NAME="${item##*#}"

  RESOLVED_IP=$(nslookup -timeout=2 "${DOMAIN}" "${SERVER}" 2>/dev/null | awk '/^Address: / {print $2}' | tail -n 1 || true)

  if [ "${RESOLVED_IP}" = "${EXPECTED_IP}" ]; then
    printf "[PASS] %-12s (%-15s) resolved %s correctly\n" "${NAME}" "${SERVER}" "${RESOLVED_IP}"
  else
    printf "[FAIL] %-12s (%-15s) returned '%s' (expected '%s')\n" "${NAME}" "${SERVER}" "${RESOLVED_IP}" "${EXPECTED_IP}"
  fi
done

# Illustrative output (reviewed against documentation)
=== Verifying DNS Propagation for: example.com ===
[PASS] Cloudflare   (1.1.1.1        ) resolved 93.184.216.34 correctly
[PASS] Google       (8.8.8.8        ) resolved 93.184.216.34 correctly
[PASS] Quad9        (9.9.9.9        ) resolved 93.184.216.34 correctly
[PASS] OpenDNS      (208.67.222.222 ) resolved 93.184.216.34 correctly

This production bash script iterates over four globally distributed recursive DNS providers, queries the domain with a strict timeout, extracts the resolved IP address using awk, and verifies consistency across providers.

Email Security and Deliverability Audit Pipeline

Validate critical email authentication records—including Mail Exchange (MX), SPF (TXT), and DMARC policies—to ensure outbound business email will not be marked as spam or rejected by recipient mail relays.

#!/usr/bin/env bash
set -euo pipefail

TARGET_DOMAIN="example.com"
echo "=== Auditing Email DNS Records for: ${TARGET_DOMAIN} ==="

echo "--- 1. Mail Exchangers (MX) ---"
nslookup -type=MX "${TARGET_DOMAIN}" | grep -E "mail exchanger" || echo "WARNING: No MX records found!"

echo "--- 2. Sender Policy Framework (SPF) ---"
nslookup -type=TXT "${TARGET_DOMAIN}" | grep -i "v=spf1" || echo "WARNING: No SPF record published!"

echo "--- 3. DMARC Alignment Policy ---"
nslookup -type=TXT "_dmarc.${TARGET_DOMAIN}" | grep -i "v=DMARC1" || echo "WARNING: No DMARC record published!"

# Illustrative output (reviewed against documentation)
=== Auditing Email DNS Records for: example.com ===
--- 1. Mail Exchangers (MX) ---
example.com     mail exchanger = 10 mail.example.com.
--- 2. Sender Policy Framework (SPF) ---
example.com     text = "v=spf1 -all"
--- 3. DMARC Alignment Policy ---
_dmarc.example.com      text = "v=DMARC1; p=reject; rua=mailto:[email protected]"

This workflow interrogates MX records, extracts SPF directives from root TXT records, and targets the standardized _dmarc subdomain to confirm that anti-spoofing policies are strictly enforced.

Pipelines, Redirection, Quoting, and Shell Expansion

When embedding nslookup inside shell pipelines (|), conditional chains (&& and ||), or command substitutions ($(...)), the calling shell performs tilde expansion, variable interpolation, and globbing before invoking the binary. Always wrap paths, patterns, and variables in quotes so whitespace and wildcard characters (*, ?) are not expanded prematurely, and use set -euo pipefail in unattended scripts.

Permissions, Security Implications, and Safe Execution

Because nslookup communicates with nameservers over standard unencrypted UDP and TCP sockets on port 53, query and response packets traverse intermediate networks in cleartext. Unencrypted DNS traffic is inherently vulnerable to eavesdropping, packet manipulation, and DNS cache poisoning attacks. For cryptographically secured resolution in production, deploy DNSSEC validation or configure DNS-over-TLS (DoT) / DNS-over-HTTPS (DoH) forwarders via local caching daemons like systemd-resolved or Unbound.

Furthermore, administrators must remember that nslookup completely bypasses local host resolution files (/etc/hosts). If you configure an internal testing host in /etc/hosts, commands like ping, curl, and ssh will resolve the override, but nslookup will fail or query the public DNS nameserver directly. Never use nslookup alone to verify application-level name resolution that relies on the glibc NSS switch.

GNU/Linux, BSD, and BusyBox Implementation Differences

The modern Linux nslookup utility is maintained by ISC as part of bind-utils (or dnsutils on Debian/Ubuntu). On FreeBSD, OpenBSD, and macOS, nslookup shares identical BIND 9 syntax and library bindings. However, Windows includes its own native nslookup.exe implementation dating back to Windows NT; while basic interactive commands (set type, server) match, command-line parameter parsing and error formatting differ between Windows and Unix shells.

In modern Linux scripting environments, many automated pipelines prefer dig over nslookup due to dig's precise output formatting (+short, +noall +answer) and detailed DNSSEC flag reporting. Nevertheless, nslookup remains the industry standard when interactive exploration or cross-platform operational consistency across Windows and Linux environments is required.

Troubleshooting Common Errors and Diagnostics

** server can't find domain: NXDOMAIN

Root Cause: The authoritative nameserver responded that the requested domain name does not exist in the DNS zone hierarchy.

Resolution: Double-check the domain spelling, verify that the record was created in the authoritative registrar DNS panel, and ensure proper subdomain delegation.

nslookup typo-domain-does-not-exist.org
# Verify authoritative delegation:
nslookup -type=SOA typo-domain-does-not-exist.org 8.8.8.8

;; connection timed out; no servers could be reached

Root Cause: Network connectivity to the configured DNS nameserver on port 53 (UDP/TCP) is blocked by a local firewall, cloud security group, or upstream ISP filter.

Resolution: Verify local outbound port 53 connectivity using netcat, check /etc/resolv.conf nameserver entries, or test using an alternate public resolver.

nc -zvw 2 8.8.8.8 53
nslookup example.com 8.8.8.8

Server failed (SERVFAIL)

Root Cause: The queried DNS server encountered an internal processing error, failed DNSSEC cryptographic signature validation, or lost upstream connectivity to root authority servers.

Resolution: Query the authoritative nameserver directly to see if the issue is DNSSEC expiration, or test with a resolver that does not enforce strict DNSSEC validation.

nslookup -type=NS example.com
# Query primary authoritative NS directly:
nslookup example.com $(nslookup -type=NS example.com | awk '/nameserver =/ {print $4}' | head -n 1)

Authoritative References and Official Documentation

Frequently Asked Questions

Quick answers to common questions and configurations

4 FAQs
Both tools query DNS servers, but dig is designed specifically for automated scripting and protocol analysis with flexible output filters (+short, +trace), whereas nslookup features an interactive command mode and is available natively across both Unix/Linux and Microsoft Windows systems.
A non-authoritative answer indicates that the queried DNS server retrieved the record from its local resolver cache rather than directly querying or hosting the authoritative master zone file for that domain.
Pass the -type=AAAA flag on the command line: nslookup -type=AAAA example.com. In interactive mode, type set type=AAAA before entering the domain name.
nslookup is a dedicated network DNS protocol debugger that directly queries nameservers over network sockets. It does not use the glibc Name Service Switch (NSS) subsystem (/etc/nsswitch.conf), meaning it intentionally ignores local static /etc/hosts overrides.
RR
Written byVerified Author

Rajesh Ray

I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.

SPAM-FREE MODERATED DISCOURSE

Join the Conversation & Perspective

Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.

AT
MP
JV
+2

No comments on this guide yet. Be the first to share your thoughts or ask a question!

Recommended Reading10 Guides

Related Technical Guides

Tested runbooks, server administration walkthroughs, and troubleshooting guides

Web Server•

How to Fix 400 Bad Request Error: 10 Easy Ways

Encountering an HTTP error can be frustrating, especially when the cause is unclear. One such error is the "400 Bad Request Error". This issue typically arises due to client-side problems, including incorrect syntax, invalid requests, or la...

RR
Rajesh Rai
Read More
Featured Infrastructure PartnerUp to 75% OFF + 3 Months Free

Supercharge Your Linux & Cloud Workloads with Hostinger

Deploy high-speed NVMe KVM VPS, Docker containers, and LiteSpeed-accelerated WordPress servers in under 60 seconds with full root access, dedicated IPv4, and 24/7 technical support.

Pure NVMe SSD StorageFull Root Access & SSHFree Domain & Unlimited SSL99.9% Uptime SLA
Plans from$2.99/mo
Claim Hostinger DealAffiliate link • Special discount applied at checkout