一、注意

nacos搭建集群比较麻烦,需要有个数据库做为数据同步。nacos给出了具体的数据库mysql。

以下是我上传的nacos脚本


也可以自己下载里面可能没有新建数据库的语句需要自己加上。

DROP DATABASE IF EXISTS `nacos`;
CREATE DATABASE `nacos` DEFAULT CHARACTER SET utf8;
USE `nacos`;

二、nacos配置文件

1、application.properties文件(加上的部分)

# 配置nacos集群nacos注册中心数据联系的数据库
spring.datasource.platform=mysql
db.num=1
# 使用的是主机名不是ip地址访问,请保证nacos和mysql数据库在同一网段
db.url.0=jdbc:mysql://mysql-nacos:3306/nacos?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true
db.user=root
db.password=123456

2、application.properties文件完整版配置文件

#
# Copyright 1999-2018 Alibaba Group Holding Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

#*************** Spring Boot Related Configurations ***************#
### Default web context path:
server.servlet.contextPath=/nacos
### Default web server port:

#*************** Network Related Configurations ***************#
### If prefer hostname over ip for Nacos server addresses in cluster.conf:
# nacos.inetutils.prefer-hostname-over-ip=false

### Specify local server's IP:
# nacos.inetutils.ip-address=
#nacos.inetutils.ip-address=192.168.79.128
#spring.cloud.inetutils.preferred-networks=192.168.79

#*************** Config Module Related Configurations ***************#
### If use MySQL as datasource:
# spring.datasource.platform=mysql

### Count of DB:
# db.num=1

### Connect URL of DB:
# db.url.0=jdbc:mysql://127.0.0.1:3306/nacos?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC
# db.user.0=nacos
# db.password.0=nacos

#*************** Naming Module Related Configurations ***************#
### Data dispatch task execution period in milliseconds: Will removed on v2.1.X, replace with nacos.core.protocol.distro.data.sync.delayMs
# nacos.naming.distro.taskDispatchPeriod=200

### Data count of batch sync task: Will removed on v2.1.X. Deprecated
# nacos.naming.distro.batchSyncKeyCount=1000

### Retry delay in milliseconds if sync task failed: Will removed on v2.1.X, replace with nacos.core.protocol.distro.data.sync.retryDelayMs
# nacos.naming.distro.syncRetryDelay=5000

### If enable data warmup. If set to false, the server would accept request without local data preparation:
# nacos.naming.data.warmup=true

### If enable the instance auto expiration, kind like of health check of instance:
# nacos.naming.expireInstance=true

nacos.naming.empty-service.auto-clean=true
nacos.naming.empty-service.clean.initial-delay-ms=50000
nacos.naming.empty-service.clean.period-time-ms=30000


#*************** CMDB Module Related Configurations ***************#
### The interval to dump external CMDB in seconds:
# nacos.cmdb.dumpTaskInterval=3600

### The interval of polling data change event in seconds:
# nacos.cmdb.eventTaskInterval=10

### The interval of loading labels in seconds:
# nacos.cmdb.labelTaskInterval=300

### If turn on data loading task:
# nacos.cmdb.loadDataAtStart=false


#*************** Metrics Related Configurations ***************#
### Metrics for prometheus
management.endpoints.web.exposure.include=*

### Metrics for elastic search
management.metrics.export.elastic.enabled=false
#management.metrics.export.elastic.host=http://localhost:9200

### Metrics for influx
management.metrics.export.influx.enabled=false
#management.metrics.export.influx.db=springboot
#management.metrics.export.influx.uri=http://localhost:8086
#management.metrics.export.influx.auto-create-db=true
#management.metrics.export.influx.consistency=one
#management.metrics.export.influx.compressed=true

#*************** Access Log Related Configurations ***************#
### If turn on the access log:
server.tomcat.accesslog.enabled=true

### The access log pattern:
server.tomcat.accesslog.pattern=%h %l %u %t "%r" %s %b %D %{User-Agent}i %{Request-Source}i

### The directory of access log:
server.tomcat.basedir=
#spring.datasource.platform=mysql
#db.num=1
#db.url.0=jdbc:mysql://10.101.167.27:3306/acm?characterEncoding=utf8&connectTimeout=1000&socketTimeout=10000&autoReconnect=true
#db.user=root
#db.password=root
spring.datasource.platform=mysql
db.num=1
# 使用的是主机名不是ip地址访问,请保证nacos和mysql数据库在同一网段
db.url.0=jdbc:mysql://mysql-nacos:3306/nacos?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true
db.user=root
db.password=123456

#*************** Access Control Related Configurations ***************#
### If enable spring security, this option is deprecated in 1.2.0:
#spring.security.enabled=false

### The ignore urls of auth, is deprecated in 1.2.0:
nacos.security.ignore.urls=/,/error,/**/*.css,/**/*.js,/**/*.html,/**/*.map,/**/*.svg,/**/*.png,/**/*.ico,/console-ui/public/**,/v1/auth/**,/v1/console/health/**,/actuator/**,/v1/console/server/**

### The auth system to use, currently only 'nacos' and 'ldap' is supported:
nacos.core.auth.system.type=nacos

### If turn on auth system:
nacos.core.auth.enabled=true

### worked when nacos.core.auth.system.type=ldap,{0} is Placeholder,replace login username
# nacos.core.auth.ldap.url=ldap://localhost:389
# nacos.core.auth.ldap.userdn=cn={0},ou=user,dc=company,dc=com

### The token expiration in seconds:
nacos.core.auth.default.token.expire.seconds=18000

### The default token:
nacos.core.auth.default.token.secret.key=SecretKey012345678901234567890123456789012345678901234567890123456789

### Turn on/off caching of auth information. By turning on this switch, the update of auth information would have a 15 seconds delay.
nacos.core.auth.caching.enabled=true

### Since 1.4.1, Turn on/off white auth for user-agent: nacos-server, only for upgrade from old version.
nacos.core.auth.enable.userAgentAuthWhite=false

### Since 1.4.1, worked when nacos.core.auth.enabled=true and nacos.core.auth.enable.userAgentAuthWhite=false.
### The two properties is the white list for auth and used by identity the request from other server.
nacos.core.auth.server.identity.key=serverIdentity
nacos.core.auth.server.identity.value=security

#*************** Istio Related Configurations ***************#
### If turn on the MCP server:
nacos.istio.mcp.server.enabled=false

#*************** Core Related Configurations ***************#

### set the WorkerID manually
# nacos.core.snowflake.worker-id=

### Member-MetaData
# nacos.core.member.meta.site=
# nacos.core.member.meta.adweight=
# nacos.core.member.meta.weight=

### MemberLookup
### Addressing pattern category, If set, the priority is highest
# nacos.core.member.lookup.type=[file,address-server]
## Set the cluster list with a configuration file or command-line argument
# nacos.member.list=192.168.16.101:8847?raft_port=8807,192.168.16.101?raft_port=8808,192.168.16.101:8849?raft_port=8809
## for AddressServerMemberLookup
# Maximum number of retries to query the address server upon initialization
# nacos.core.address-server.retry=5
## Server domain name address of [address-server] mode
# address.server.domain=jmenv.tbsite.net
## Server port of [address-server] mode
# address.server.port=8080
## Request address of [address-server] mode
# address.server.url=/nacos/serverlist

#*************** JRaft Related Configurations ***************#

### Sets the Raft cluster election timeout, default value is 5 second
# nacos.core.protocol.raft.data.election_timeout_ms=5000
### Sets the amount of time the Raft snapshot will execute periodically, default is 30 minute
# nacos.core.protocol.raft.data.snapshot_interval_secs=30
### raft internal worker threads
# nacos.core.protocol.raft.data.core_thread_num=8
### Number of threads required for raft business request processing
# nacos.core.protocol.raft.data.cli_service_thread_num=4
### raft linear read strategy. Safe linear reads are used by default, that is, the Leader tenure is confirmed by heartbeat
# nacos.core.protocol.raft.data.read_index_type=ReadOnlySafe
### rpc request timeout, default 5 seconds
# nacos.core.protocol.raft.data.rpc_request_timeout_ms=5000

#*************** Distro Related Configurations ***************#

### Distro data sync delay time, when sync task delayed, task will be merged for same data key. Default 1 second.
# nacos.core.protocol.distro.data.sync.delayMs=1000

### Distro data sync timeout for one sync data, default 3 seconds.
# nacos.core.protocol.distro.data.sync.timeoutMs=3000

### Distro data sync retry delay time when sync data failed or timeout, same behavior with delayMs, default 3 seconds.
# nacos.core.protocol.distro.data.sync.retryDelayMs=3000

### Distro data verify interval time, verify synced data whether expired for a interval. Default 5 seconds.
# nacos.core.protocol.distro.data.verify.intervalMs=5000

### Distro data verify timeout for one verify, default 3 seconds.
# nacos.core.protocol.distro.data.verify.timeoutMs=3000

### Distro data load retry delay when load snapshot data failed, default 30 seconds.
# nacos.core.protocol.distro.data.load.retryDelayMs=30000

3、custom.properties文件(nacos管理客户端配置)

#spring.security.enabled=false
#management.security=false
#security.basic.enabled=false
#nacos.security.ignore.urls=/**
#management.metrics.export.elastic.host=http://localhost:9200
# metrics for prometheus
management.endpoints.web.exposure.include=*

# metrics for elastic search
#management.metrics.export.elastic.enabled=false
#management.metrics.export.elastic.host=http://localhost:9200

# metrics for influx
#management.metrics.export.influx.enabled=false
#management.metrics.export.influx.db=springboot
#management.metrics.export.influx.uri=http://localhost:8086
#management.metrics.export.influx.auto-create-db=true
#management.metrics.export.influx.consistency=one
#management.metrics.export.influx.compressed=true

三、nginx配置文件

user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;
    
    upstream nacos {   
      server nacos1:8848;
      server nacos2:8848;
    }

    # 导入其他配置文件的内容
    #include /etc/nginx/conf.d/*.conf;

server {
    listen       8848;
    server_name  localhost;

    #charset koi8-r;
    #access_log  /var/log/nginx/host.access.log  main;

    location / {
        #root   /usr/share/nginx/html;
        #index  index.html index.htm;
        proxy_pass http://nacos;
    }

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}
}

四、docker-compones文件

version: '2'
services:
  mysql:
    # 根据mysql:5.7镜像生成容器格式:名字:版本
    image: mysql:5.7
    # 网络中主机名
    hostname: mysql-nacos
    # 容器镜像名
    container_name: mysql-nacos
    # 最大内存大小
    mem_limit: 512M
    # 对外暴露的端口格式:宿主机端口:容器端口
    ports:
     - 13306:3306
     
  nginx:
    image: nginx
    hostname: nginx-nacos
    container_name: nginx-nacos
    mem_limit: 512M
    ports:
     - 8848:8848
    # 将容器文件挂载宿主机格式:宿主机文件位置:容器文件位置
    volumes:
     - ./nginx/log:/var/log/nginx
     - ./nginx/conf/nginx.conf:/etc/nginx/nginx.conf
     - ./nginx/conf.d:/etc/nginx/conf.d
     
  nacos1:
    image: nacos/nacos-server
    hostname: nacos1
    container_name: nacos1
    mem_limit: 512M
    # 给予容器:真正的root的权限
    privileged: true
    ports:
     - 18848:8848
    volumes: #挂载
     - ./nacos1:/home/nacos/logs
     - ./nacos/init.d/custom.properties:/home/nacos/init.d/custom.properties
     - ./nacos/conf/application.properties:/home/nacos/conf/application.properties
    # 环境参数
    environment:
     # 什么模式:集群模式
     MODE: cluster
     # 电脑的识别方式:主机名识别
     PREFER_HOST_MODE: hostname
     # 集群包含的服务器:用逗号隔开
     NACOS_SERVERS: nacos1:8848,nacos2:8848
     
  nacos2:
    image: nacos/nacos-server
    hostname: nacos2
    container_name: nacos2
    mem_limit: 512M
    privileged: true
    ports:
     - 18849:8848
    volumes:
    # 日志文件挂载到宿主机
     - ./nacos2:/home/nacos/logs
    # 客户端管理配置文件挂载到宿主机
     - ./nacos/init.d/custom.properties:/home/nacos/init.d/custom.properties
    # nacos集群配置文件挂载到宿主机
     - ./nacos/conf/application.properties:/home/nacos/conf/application.properties
    environment:
     MODE: cluster
     PREFER_HOST_MODE: hostname
     NACOS_SERVERS: nacos1:8848,nacos2:8848

# 设置网络
networks:
  default:
   external:
      # 创建好的网络的名字:之所以设置是要把mysql和nacos的网络在同一频道,保证其可以正常访问。
      name: jt47

五、运行docker-componse文件创建

命令:docker-compose up(创建文件中所有的容器)

docker-compose up nacos1(创建文件中容器标签为:nacos1容器)

六、注意:

    1. 要保证mysql和nacos在同一网段下,不然数据无法进行共享
    networks: default: external: name: jt47(网络名称)2. 要给予nacos真正的nacos权限(不设置的时候是普通的root权限):
    privileged:true3. 环境参数:
    1. 要保证是集群模式
    environment: MODE: cluster2. 要保证能够访问nacos设置使用主机名识别连接(因为ip地址是可变的)
    environment:
    PREFER_HOST_MODE: hostname3. 配置nacos集群nacos服务ip
    environment:
    NACOS_SERVERS: nacos1:8848,nacos2:88484. 要为客户端管理配置文件加上一句内容(custom.properties文件)
    management.endpoints.web.exposure.include=*