Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Configuring Nacos as Service Registry and Configuration Center in Microservices

Tech May 8 4

Overview

Nacos, developed by Alibaba, serves as a dynamic naming and configuration service that combines service registration and configuration management into a single platform. This guide walks through setting up and utilizing Nacos within microservice environments.

Core Features of Nacos

Nacos provides two primary functionalities:

  • Service Registration and Discovery: Replaces tools like Eureka or Consul, offering automatic registration, health checks, and load balancing.
  • Dynamic Configuration Management: Centralizes configuration files, enabling runtime updates without service restarts and supporting environment-specific configurations.

This tutorial uses Nacos version 2.1.0, compatible with Spring Cloud Alibaba 2.2.x and later versions.

Installing Nacos Server

Single Node Deployment (Development Environment)

Option 1: Using Docker

Pull the official image:


docker pull nacos/nacos-server:v2.1.0-slim

Create directories for logs and configuration:

mkdir -p /mydata/nacos/logs/
mkdir -p /mydata/nacos/conf/

Start a temporary container to extract default configurations:


docker run -d --name nacos-server -p 8848:8848 nacos/nacos-server:v2.3.1

Copy configuration files to host directories:


docker cp nacos-server:/home/nacos/logs/ /mydata/nacos/
docker cp nacos-server:/home/nacos/conf/ /mydata/nacos/

Remove the temporary container:


docker rm -f nacos-server

Set up MySQL database for production-grade deployment:

-- Create database
CREATE DATABASE IF NOT EXISTS nacos-mysql-config;

-- Table definitions for Nacos configuration tables
-- (Refer to full schema in original document)

Launch the Nacos server with persistence:


docker run -d \
  --name nacos \
  -p 8848:8848 \
  -p 9848:9848 \
  -p 9849:9849 \
  --privileged=true \
  -e JVM_XMS=256m \
  -e JVM_XMX=256m \
  -e JVM_XMN=128m \
  -e MODE=standalone \
  -e SPRING_DATASOURCE_PLATFORM=mysql \
  -e MYSQL_SERVICE_HOST=your-db-host \
  -e MYSQL_SERVICE_PORT=3306 \
  -e MYSQL_SERVICE_DB_NAME=nacos-mysql-config \
  -e MYSQL_SERVICE_USER=root \
  -e MYSQL_SERVICE_PASSWORD=your-db-password \
  -e NACOS_AUTH_TOKEN=your-encrypted-token \
  -e NACOS_AUTH_IDENTITY_KEY=nacos \
  -e NACOS_AUTH_IDENTITY_VALUE=secret \
  -v /mydata/nacos/logs/:/home/nacos/logs \
  -v /mydata/nacos/conf/:/home/nacos/conf/ \
  --restart=always \
  nacos/nacos-server:v2.1.0-slim

Ensure ports 8848, 9848, and 9849 are accessible via firewall.

Access the web console at:

http://your-ip:8848/nacos

Default credentials: nacos/nacos

Option 2: Source Package Installation

  1. Download the Nacos 2.1.0 package from the official site.
  2. Extract and navigate to the bin directory.
  3. Run:
# On Linux/macOS
sh startup.sh -m standalone

# On Windows
startup.cmd -m standalone

Verify successful startup by accessign the console at http://server-ip:8848/nacos.

Integrating with Spring Cloud Applications

Maven Dependencies

Add the following dependencies to pom.xml:

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
    <version>2.2.7.RELEASE</version>
</dependency>

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
    <version>2.2.7.RELEASE</version>
</dependency>

Application Configuration

Configure service registration in application.yml:

spring:
  cloud:
    nacos:
      discovery:
        server-addr: your-nacos-host:8848
        username: nacos
        password: nacos
      config:
        server-addr: your-nacos-host:8848
        group: DEFAULT_GROUP
        file-extension: yml
  config:
    import:
      - optional:nacos:${spring.application.name}.${spring.cloud.nacos.config.file-extension}

Enable Service Discovery

Annotate your main application class:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient
public class EBuiltAuthenticApplication {
    public static void main(String[] args) {
        SpringApplication.run(EBuiltAuthenticApplication.class, args);
    }
}

After starting the service, it should appear in the Nacos service list.

Using Dynamic Configuration Center

Bootstrap Configuration

Use bootstrap.yml for configuration center settings:

spring:
  application:
    name: e-built-authentic
  cloud:
    nacos:
      config:
        server-addr: your-nacos-host:8848
        file-extension: yaml
        group: DEFAULT_GROUP
        username: nacos
        password: nacos

Adding Configuration in Nacos Console

In the console, go to "Configuration Management" → "Configuration List", then click "+" to create a new configuration:

  • Data ID: e-built-authentic.yaml
  • Group: DEFAULT_GROUP
  • Configuration Content:
user:
  name: nacos-test
  age: 18

Accessing Configuration Values

Use the @Value annotation in a controller with @RefreshScope:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RefreshScope
public class ConfigController {

    @Value("${user.name:default}")
    private String userName;

    @GetMapping("/user/name")
    public String getUserName() {
        return userName;
    }
}

Access /user/name to retrieve the configured value. Modifying the value in Nacos will reflect immediately without restarting the service.

Troubleshooting Common Issues

Service Registration Failure

Error: Client not connected

Solution: Verify network connectivity and ensure ports 8848, 9848–9849 are open.

Authentication Failure

Error: Authentication failed

Solution: Confirm that authentication parameters match between client and server.

Configuration Not Applied

Error: Default values returned

Solution: Check that the Data ID matches the pattern service-name.file-extension and the Group is consistent.

Production Considerations

  1. Cluster Deployment: Use a cluster setup to prevent single points of failure.
  2. Database Persistence: Configure MySQL instead of default memory storage.
  3. Security Settings: Enable authentication and set strong tokens.
  4. Version Compatibility: Ensure compatibility between Nacos and Spring Cloud Alibaba versions.

Conclusion

Nacos simplifies service discovery and configuration management in microservices. This guide covers essential setup steps for development and production environments. Further exploration can include advanced features like configuration gray release and service routing.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

SBUS Signal Analysis and Communication Implementation Using STM32 with Fus Remote Controller

Overview In a recent project, I utilized the SBUS protocol with the Fus remote controller to control a vehicle's basic operations, including movement, lights, and mode switching. This article is aimed...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.