Cloud Native 34 min read

Master Nacos: Complete Guide to Architecture, Registration, and Configuration Management

This comprehensive guide explains Nacos's architecture, registration center, configuration center, deployment modes, data models, service discovery, health monitoring, dynamic configuration, multi‑environment support, and real‑time refresh mechanisms, providing practical code examples and operational best practices.

Architect's Alchemy Furnace
Architect's Alchemy Furnace
Architect's Alchemy Furnace
Master Nacos: Complete Guide to Architecture, Registration, and Configuration Management

Nacos Authoritative Guide

1. Nacos Architecture

1.1 Basic Architecture

1.2 Logical Architecture

Service Management: CRUD for services and domains, health checks, weight management, etc.

Configuration Management: CRUD for configurations, versioning, gray release, listeners, push tracking, aggregation.

Metadata Management: CRUD and tagging capabilities.

Plugin Mechanism: SPI‑based extensibility.

Event Mechanism: Asynchronous event notification and SDK data change alerts.

Logging Module: Log categories, levels, portability, formatting, error codes with documentation.

Callback Mechanism: Unified SDK callbacks with extensible interfaces.

Addressing Modes: Support for IP, domain, nameserver, broadcast, etc., with extensibility.

Push Channels: Optimize push performance between server‑storage, server‑server, and server‑SDK.

Capacity Management: Tenant‑ and group‑level capacity limits to avoid storage overflow.

Traffic Management: Rate limiting, long‑connection count, payload size, flow control per tenant/group.

Cache Mechanism: Disaster‑recovery directories, local cache, server cache.

Startup Modes: Standalone, configuration, service, DNS, or all‑mode launches.

Consistency Protocols: Different consistency mechanisms for varied data and requirements.

Storage Module: Persistent and non‑persistent storage, data sharding.

Nameserver: Routing from namespace to cluster ID, mapping user environment to physical Nacos.

CMDB: Metadata storage and integration with third‑party CMDB systems.

Metrics: Standard metrics exposure for third‑party monitoring.

Trace: Standard trace exposure for SLA, log flattening, push tracking, and billing integration.

Access Management: Service provisioning similar to Alibaba Cloud, handling identity, capacity, permissions.

User Management: Login, SSO, etc.

Permission Management: Identity verification, access control, role management.

Audit System: Extensible interfaces for various company audit integrations.

Notification System: Core data change notifications via SMS or other channels.

OpenAPI: Standard REST‑style HTTP interface, simple and multi‑language friendly.

Console: User‑friendly UI for service and configuration operations.

SDK: Multi‑language SDKs.

Agent: DNS‑like mode or integration with mesh solutions.

CLI: Git‑like lightweight command‑line management.

1.3 Domain Model

1.3.1 Data Model

Nacos data model keys are uniquely identified by a triple; the default namespace is an empty string, the public namespace is public, and the default group is DEFAULT_GROUP.

1. Group+DataId combination is unique, i.e., within the same group there cannot be multiple configurations with the same DataId.

2. Group isolation ensures services registered under different groups cannot be called via OpenFeign by specifying the service name.

3. Namespace+Group+DataId combination is unique; the same DataId can appear in different namespaces, but within a single namespace the pair Group+DataId must be unique.

1.3.2 Service Domain Model

1.3.3 Configuration Domain Model

Configuration is associated with two entities: configuration change history and service tags (used for classification and indexing), linked by ID.

1.3.4 Build, Deploy and Startup Modes

2. Registration Center

2.1 Role of the Registration Center

Service Registration: Instances register name, address, port, etc., on startup.

Service Discovery: Consumers pull service lists or receive push updates.

Health Checking: Periodic health checks filter unhealthy instances.

Service Routing: Determines request distribution, usually via load‑balancing strategies.

Service Monitoring: Monitors response time, error rate, etc.

Service Update: Notifies the registry when instance information changes.

2.2 Evolution of the Registration Center

Monolithic era: Direct calls between services.

Growth of order service instances leads to multiple instances.

Using Nginx to maintain an IP list.

Concept of a registration center emerges.

2.3 Nacos Registration Center

2.3.1 Nacos Features

Nacos offers simple, easy‑to‑use features for dynamic service discovery, health monitoring, and configuration management.

Service Discovery

Nacos supports DNS‑based and RPC‑based discovery. Providers register via SDK, OpenAPI, or an Agent; consumers discover services via DNS or HTTP/API.

Service Health Monitoring

Real‑time health checks prevent requests from reaching unhealthy instances and provide a health‑check dashboard.

Dynamic Configuration Service

Centralized, externalized, and dynamic configuration management eliminates the need for redeployment when configs change.

Dynamic configuration also simplifies stateless service implementation and elastic scaling.

Nacos UI offers configuration version tracking, canary releases, one‑click rollback, and client update status tracking.

Dynamic DNS Service

Provides simple DNS resolution for load balancing, traffic control, and intra‑data‑center name resolution.

Service and Metadata Management

From a micro‑service platform perspective, Nacos manages service descriptions, lifecycles, static dependency analysis, health status, traffic control, routing, security policies, SLA, and metrics.

2.3.2 Nacos Service Registration Process

Figure 1: Nacos service registration and discovery.

The diagram involves three roles:

Register Service (Nacos Server): Provides registration and discovery for providers and consumers.

Provider Service (Nacos Client): Registers itself to the server for external consumption.

Consumer Service (Nacos Client): Retrieves the service list from the server and invokes providers.

Registration and discovery steps:

Download and run Nacos Server from the official site.

When a provider starts, it registers its spring.application.name to the server.

When a consumer starts, it also registers itself.

The consumer obtains the full service list (including itself) from the server.

Using HTTP or messaging middleware, the consumer calls the provider's service.

2.4 Nacos OpenAPI

Exposes a standard REST‑style HTTP interface for easy multi‑language integration. Documentation: Open API Guide

3. Configuration Center

3.1 DataId Naming

Rule: ${prefix}-${spring.profiles.active}.${file-extension}

${prefix}: defaults to spring.application.name ${spring.profiles.active}: current environment profile (supports multiple environments)

${file-extension}: file format extension

Common conventions:

{spring.application.name}.yaml

{spring.application.name}-{spring.profiles.active}.yaml (higher priority)

3.2 Configuration Priority

{spring.application.name}-{spring.profiles.active}.yaml > {spring.application.name}.yaml > application.yml (local)

Main config > extension-configs > shared-configs

Within extension-configs: higher index = higher priority (e.g., extension-configs[3] > ... > [0])

Within shared-configs: same rule applies.

Rule of thumb: more specific > remote > larger index.

Note: Nacos configuration must be placed in bootstrap.yml or bootstrap.properties , not in application.yml / application.properties . Bootstrap loads before the main application context, and its values are never overridden by later loads.

3.3 Multi‑Environment Support

Different namespaces for multi‑tenant, multi‑project, or multi‑system isolation (set namespace in bootstrap.yaml).

Same namespace with different DataId for dev/test/prod environments (switch spring.profiles.active).

spring:
  profiles:
    active: dev
  application:
    name: demo1
  cloud:
    nacos:
      server-addr: 10.0.110.62:8848
      namespace: 7c6f53f2-926e-4bf1-848a-a5461f1c9e36

3.4 Shared Configuration

Common configurations (e.g., DB, Redis, MQ) can be placed in shared files for easier maintenance.

spring:
  cloud:
    nacos:
      server-addr: 10.0.110.62:8848
      namespace: 7c6f53f2-926e-4bf1-848a-a5461f1c9e36
      refresh-enabled: true
      file-extension: yaml
      config:
        extension-configs:
          - refresh: true
            group: DEFAULT_GROUP
            data-id: redis.yaml
          - refresh: true
            group: DEFAULT_GROUP
            data-id: mysql.yaml
          - refresh: true
            group: DEFAULT_GROUP
            data-id: kafka.yaml
          - refresh: true
            group: DEFAULT_GROUP
            data-id: activemq.yaml
        shared-configs[0]:
          - refresh: true
            group: DEFAULT_GROUP
            data-id: redis.yaml

3.5 Configuration Refresh

Push + Pull for Real‑Time Client Config Updates After registering a Listener, Nacos builds an RPC channel to the server, sends a change‑query request, and the server compares MD5 hashes to return changed keys. The client then pulls the changed content and invokes the Listener. Short polling (continuous requests) wastes resources; long polling holds the request on the server side and returns immediately when a change occurs, reducing load and latency. Nacos implements long polling with a ~30‑second hold period; a change triggers an event that pushes the new config to the client.

To enable automatic refresh, annotate beans with @RefreshScope. When a configuration changes, Nacos publishes a RefreshEvent, the context refreshes the environment, clears the bean cache, and recreates beans with the new values.

import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.sql.SQLException;
import java.util.List;

@RestController
@RequestMapping("consumer")
@RefreshScope
public class ConsumerController {
    private ProducerFeign producer;
    private JdbcTemplate template;

    public ConsumerController(ProducerFeign producer, JdbcTemplate template) {
        this.producer = producer;
        this.template = template;
    }

    @Value("${id}")
    private String id;

    @GetMapping("getMessage")
    public String consumerMessage() {
        return producer.consumer("ready");
    }

    @GetMapping("getPort")
    public String consumerPort() throws SQLException {
        List<String> result = template.queryForList("SELECT canvas_name FROM graph", String.class);
        return " Receive request server id:" + id + " data:" + result.get(0);
    }
}

The @RefreshScope annotation extends @Scope with a proxy mode (default TARGET_CLASS). When a config change occurs, a RefreshEvent triggers ContextRefresher.refresh(), which refreshes the environment and calls RefreshScope.refreshAll() to clear the cache and recreate beans.

/**
 * Convenience annotation to put a @Bean definition in refresh scope.
 */
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Scope("refresh")
@Documented
public @interface RefreshScope {
    ScopedProxyMode proxyMode() default ScopedProxyMode.TARGET_CLASS;
}

Underlying generic scope caches bean instances; on refresh the cache is cleared, and new bean instances are created with updated configuration values.

4. Operations Guide

4.1 Nacos Deployment Modes

Standalone – for testing or single‑node usage.

Cluster – production‑grade high availability.

Multi‑Cluster – multi‑data‑center scenarios.

4.1.1 Standalone Mode

Linux/Unix/Mac

# Standalone means it is non‑cluster Mode.
$ sh startup.sh -m standalone

Windows

# Standalone means it is non‑cluster Mode.
$ cmd startup.cmd -m standalone

MySQL Support

From version 0.7, Nacos can use MySQL as the data source. Configure conf/application.properties with the JDBC URL, username, and password.

spring.datasource.platform=mysql
db.num=1
db.url.0=jdbc:mysql://11.162.196.16:3306/nacos_devtest?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true
db.user=nacos_devtest
db.password=youdontknow

4.1.2 Cluster Mode

Define node IPs in conf/cluster.conf (at least three nodes).

# ip:port
200.8.9.16:8848
200.8.9.17:8848
200.8.9.18:8848

Optionally enable the built‑in authentication plugin by setting the following in conf/application.properties (replace the secret values with your own):

nacos.core.auth.enabled=true
nacos.core.auth.system.type=nacos
nacos.core.auth.plugin.nacos.token.secret.key=${your_secret_key}
nacos.core.auth.server.identity.key=${your_identity_key}
nacos.core.auth.server.identity.value=${your_identity_value}

Start the cluster:

# Embedded data source
sh startup.sh -p embedded
# External data source
sh startup.sh

4.1.3 Multi‑Cluster Mode

Nacos supports NameServer routing to direct requests to specific clusters based on namespace, tenant, or other criteria.

4.1.4 Multi‑Network‑Card IP Selection

Configure IP selection in conf/application.properties:

nacos.inetutils.ip-address=10.11.105.155
nacos.inetutils.use-only-site-local-interfaces=true
nacos.inetutils.ignored-interfaces[0]=eth0
nacos.inetutils.ignored-interfaces[1]=eth1
nacos.inetutils.preferred-networks[0]=30.5.124.

4.2 Service Traffic Weight and Protection

Nacos allows per‑instance weight adjustment and traffic threshold protection. Set weight to 0 to stop traffic, increase weight to raise traffic share.

4.3 Graceful Service Up/Down

Instances can be manually taken offline or brought online via the console; offline instances are excluded from the healthy list.

Microservicesservice discoveryConfiguration ManagementNacosSpring Cloud
Architect's Alchemy Furnace
Written by

Architect's Alchemy Furnace

A comprehensive platform that combines Java development and architecture design, guaranteeing 100% original content. We explore the essence and philosophy of architecture and provide professional technical articles for aspiring architects.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.