DNS解析过程中如何利用服务端口?附Consul与Registrator实践场景
Nice setup you've got there with Consul, Registrator, and Docker! Let's walk through how to use service ports during DNS resolution for your Redis service (and others you might deploy):
1. Understand Consul DNS Record Types
Consul's built-in DNS service (running on port 8600 by default) provides two key record types for service discovery, and you'll need the right one to get port details:
- A Records: These return the IP address of your Redis container, but don't include port info. You can test this with:
dig @localhost -p 8600 redis.service.consul - SRV Records: This is what you need for port information! SRV records are designed explicitly to map service names to their host and port. Run this command to fetch Redis's port:
The output will include the random port Docker assigned (since you useddig @localhost -p 8600 SRV redis.service.consul-Pin your run command) along with the container's IP.
2. Resolve SRV Records in Your Applications
Most modern programming languages and service discovery libraries support SRV record resolution, so you can dynamically fetch the port without hardcoding it. For example, in Python using the dnspython library:
import dns.resolver # Query Consul DNS for Redis's SRV record try: srv_records = dns.resolver.resolve('redis.service.consul', 'SRV') for record in srv_records: redis_host = str(record.target).rstrip('.') # Remove trailing dot redis_port = record.port print(f"Connecting to Redis at {redis_host}:{redis_port}") # Use these values to initialize your Redis client except dns.resolver.NXDOMAIN: print("Redis service not found in Consul")
3. Optional: Use Fixed Ports for Predictability
If you prefer not to use Docker's random port assignment (via -P), you can map a fixed port when starting your container:
docker run -d -p 6379:6379 --name=redis redis
Registrator will automatically register this fixed 6379 port with Consul, so you can either use SRV records (still reliable) or even hardcode the port if you're confident it won't conflict—though dynamic resolution is always better for scalability.
4. Verify Consul DNS is Enabled
Double-check that Consul's DNS service is active (it's enabled by default, but good to confirm):
- Look for
dns_config { enable = true }in your Consul agent config file, or - Run
consul agent -config-dir=/path/to/configwith DNS enabled (no extra flag needed unless you've disabled it previously)
Since you've already confirmed Registrator is registering Redis with Consul via the API, the DNS layer should pick up that port info automatically—you just need to query the right record type!
内容的提问来源于stack exchange,提问作者blueFast

