前言

环境:centos7.9、k8s 1.22.15 、docker 20.10.9、nacos-server-2.2.2.tar.gz
nacos是一个用于构建云原生应用的动态服务发现、配置管理和服务管理平台,简称服务配置注册管理中心。

Nacos支持三种部署模式

单机模式 - 用于测试和单机试用。
集群模式 - 用于生产环境,确保高可用。
多集群模式 - 用于多数据中心场景

本篇不讲多集群模式。本篇讲传统方式、docker方式、k8s方式部署nacos单机版和cluster版。

官方文档

官方部署文档:https://nacos.io/zh-cn/docs/deployment.html
nacos的github官网:https://github.com/alibaba/nacos/tree/master
nacos建议的使用k8s部署nacos文档:https://nacos.io/en-us/docs/use-nacos-with-kubernetes.html
nacos的k8s helm 项目:
git clone https://github.com/nacos-group/nacos-k8s.git
https://github.com/nacos-group/nacos-k8s/tree/master/helm

二进制部署nacos(单机模式)

nacos的github官网:https://github.com/alibaba/nacos/tree/master

安装jdk

nacos 依赖jdk,所以需要安装jdk:查看这篇https://blog.csdn.net/MssGuo/article/details/120097813

wget https://download.oracle.com/java/17/latest/jdk-17_linux-x64_bin.tar.gz
tar  xf jdk-17_linux-x64_bin.tar.gz -C /usr/local/
mv /usr/local/jdk-17.0.6/ /usr/local/java
vim /etc/profile	#添加下面3行
export JAVA_HOME=/usr/local/java
export CLASSPATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
export PATH=$PATH:$JAVA_HOME/bin

source  /etc/profile
java -version

创建数据库及用户名

#我的数据库是8.0.32  
#去到mysql数据库服务器手动执行创建nacos-config数据库语句以及创建nacos用户
[root@mysql ~]# mysql -uroot -p'123456'
#只所以叫nacos_config,是因为官方压缩包里面的创建nacos表结构的sql文件中说数据库全名叫nacos_config
mysql> create database nacos_config character set utf8;			
mysql> create user 'nacos'@'%' identified by 'nacos';
mysql> grant all privileges ON nacos_config.* TO 'nacos'@'%';

下载安装包并解压

wget -c https://github.com/alibaba/nacos/releases/download/2.2.2/nacos-server-2.2.2.tar.gz
tar xvf nacos-server-2.2.2.tar.gz
cd nacos/conf
[root@master conf]# ll *.sql*
-rw-r--r-- 1 502 games  1224 313 11:54 1.4.0-ipv6_support-update.sql
-rw-r--r-- 1 502 games  8939 329 15:21 derby-schema.sql			#这个不用管,我们不使用derby数据库
-rw-r--r-- 1 502 games 10825 43 16:33 mysql-schema.sql

导入nacos的表结构

#将sql文件传输到mysql服务器
[root@master conf]# scp mysql-schema.sql  1.4.0-ipv6_support-update.sql  root@192.168.158.131:/root/
#开始导入数据
[root@cicd ~]# mysql -unacos -p'nacos'
mysql> use nacos_config;
Database changed
mysql> source /root/mysql-schema.sql;
mysql> source /root/1.4.0-ipv6_support-update.sql;
mysql> show tables;					#检查
+------------------------+
| Tables_in_nacos_config |
+------------------------+
| config_info            |
| config_info_aggr       |
| config_info_beta       |
| config_info_tag        |
| config_tags_relation   |
| group_capacity         |
| his_config_info        |
| permissions            |
| roles                  |
| tenant_capacity        |
| tenant_info            |
| users                  |
+------------------------+
12 rows in set (0.00 sec)

mysql> select * from users;			#检查用户表,nacos浏览器页面登录的账号/密码就是nacos/nacos
+----------+--------------------------------------------------------------+---------+
| username | password                                                     | enabled |
+----------+--------------------------------------------------------------+---------+
| nacos    | $2a$10$EuWPZHzz32dJN7jexM34MOeYirDdFAZm2kuWj7VEOJhhZkDrxfvUu |       1 |
+----------+--------------------------------------------------------------+---------+
1 row in set (0.00 sec)
mysql> 

修改配置文件,启动nacos,登录nacos

[root@master ~]# cd nacos/conf
[root@master conf]# vim application.properties			#编辑配置文件,主要是修改或取消注释下面这些参数
[root@master conf]# grep -Ev '$^|#' application.properties
server.servlet.contextPath=/nacos						#保持默认,这是URL的上下文,业务页面访问的时候需要加这个上下文
server.error.include-message=ALWAYS						#保持默认
server.port=8848										#保持默认,nacos端口
nacos.inetutils.ip-address=192.168.158.128				#nacos绑定的IP地址,不写默认监听全部地址
spring.sql.init.platform=mysql							#去掉注释,开启这个参数
db.num=1												#去掉注释,开启这个参数,数据库的数量
#填写数据库连接信息,192.168.158.131:3306是数据库的IP地址和端口,nacos_config是nacos数据库名称
db.url.0=jdbc:mysql://192.168.158.131:3306/nacos_config?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC
db.user.0=nacos											#nacos数据库的用户名,前面我们设置的用户就是nacos
db.password.0=nacos										#nacos数据库的密码,前面我们设置的nacos用户密码就是nacos				
nacos.core.auth.system.type=nacos						#保持默认
nacos.core.auth.enabled=true							#取消注释,值改为true,参数含义为是否启用nacos账号密码登录

# 这个地址https://nacos.io/zh-cn/docs/v2/guide/user/auth.html说明了认证相关的参数怎么配置
#下面这两个参数随便设置一个key/value值,官方说了在nacos-2.2.1版本之后为了安全考虑无默认值,需要自己填写
nacos.core.auth.server.identity.key=nacos
nacos.core.auth.server.identity.value=nacos

#下面这个参数官方也说了nacos-2.2.1版本之后为了安全考虑无默认值,需要自己填写
#同时,需要使用一个不少于32个字符的字符串进行base64进行加密,如 echo "bmFjb3MgaXMgdmVyeSBnb29kIHNvZnR3YXJlCg==" | base64
nacos.core.auth.plugin.nacos.token.secret.key=Ym1GamIzTWdhWE1nZG1WeWVTQm5iMjlrSUhOdlpuUjNZWEpsQ2c9PQo=
[root@master nacos]# vim bin/statrup.sh					#编辑启动脚本,修改一个参数
export MODE="standalone"								#原来是cluster,改为standalone,因为我们要使用单机模式启动nacos
#单机模式启动nacos
[root@master nacos]# cd bin/
[root@master bin]# bash startup.sh   					#单机模式启动nacos

#如果你没有修改statrup.sh脚本里面的MODE变量值为"standalone",则这样直接在启动时指定模式也可以:
[root@master bin]# bash start.sh  -m standalone

#查看日志,日志在logs命令
[root@master nacos]# tail -2222f  logs/start.out
在日志中如果nacos正常启动,其web登录页面为:http://192.168.158.128:8848/nacos/index.html
在浏览器登录,账号密码默认是nacos nacos,建议登录后立即修改密码;
接下来就是权限控制--权限管理-添加权限-为public命名空间添加ROLE_ADMIN角色;
添加命名空间--分配角色等基本操作,可以正常使用nacos了。

问题记录:
1、如果需要账号密码登录web页面nacos,需要自己设置auth相关的参数,这是因为此nacos-2.2.1版本修改了认证的方式,和以前的nacos版本有所不
同了,详见https://nacos.io/zh-cn/docs/v2/guide/user/auth.html。
2、在浏览器登录nacos的使用,使用start.out日志官方给出了登录地址,http://192.168.158.128:8848/nacos/index.html登录,发现总是提示
一个"user not found!权限认证失败,没有命名空间的访问权限" 这个弹窗,即使登录进去给所有的命名空间绑定ROLE_ADMIN角色,还是一样。后来
发现使用http://192.168.158.128:8848/nacos/index.html时,URL会自动补全http://192.168.158.128:8848/nacos/index.html#/login?
namespace=&pageSize=&pageNo=,怀疑就是由于后面补全的这段URL造成的,后来直接使用http://192.168.158.128:8848/nacos/#/login就再也
没有弹窗提示了。
#下面是nacos-server-2.2.1版本的安装
#安装nacos
mkdir nacos-server
wget -c https://github.com/alibaba/nacos/releases/download/2.2.1/nacos-server-2.2.1.tar.gz
tar xvf nacos-server-2.2.1.tar.gz
cd nacos 
vim conf/application.properties			#添加下面的链接mysql的语句,注意修改mysql的IP和root密码
# db mysql
spring.datasource.platform=mysql
db.num=1
db.url.0=jdbc:mysql://192.168.544.150:3306/ry-config?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC
db.user=root
db.password=Aa123456

#发现启动报错,显示登录鉴权相关的报错,官网说2.2.2之后才需哟自己配置登录信息,不知道2.2.1为什么也要配置,所已就配置:
#修改下面这个几个参数的值
nacos.core.auth.enabled=true
nacos.core.auth.server.identity.key=nacos
nacos.core.auth.server.identity.value=nacos
nacos.core.auth.plugin.nacos.token.secret.key=VkdocGMwbHpUWGxEZFhOMGIyMVRaV055WlhSTFpYa3dNVElocGMwbHpUWGxEZFhOMGIyMVRaV055WlhSTFpYa3dhZmR6TkRVMk56Zz0K

#单机模式启动nacos
cd bin/
 ./startup.sh  -m standalone
./startup.sh  -m standalone; tail -222f /root/nacos-server/nacos/logs/start.out

二进制部署nacos(cluster模式)

nacos的cluster模式采用:3台nacos+nginx

安装jdk(3台都安装jdk)

nacos 依赖jdk,所以需要安装jdk:查看这篇https://blog.csdn.net/MssGuo/article/details/120097813

wget https://download.oracle.com/java/17/latest/jdk-17_linux-x64_bin.tar.gz
tar  xf jdk-17_linux-x64_bin.tar.gz -C /usr/local/
mv /usr/local/jdk-17.0.6/ /usr/local/java
vim /etc/profile	#添加下面3行
export JAVA_HOME=/usr/local/java
export CLASSPATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
export PATH=$PATH:$JAVA_HOME/bin

source  /etc/profile
java -version

创建数据库及用户名,导入数据库

#我的数据库是8.0.32  
#去到mysql数据库服务器手动执行创建nacos-config数据库语句以及创建nacos用户
[root@mysql ~]# mysql -uroot -p'123456'
#只所以叫nacos_config,是因为官方压缩包里面的创建nacos表结构的sql文件中说数据库全名叫nacos_config
mysql> create database nacos_config character set utf8;			
mysql> create user 'nacos'@'%' identified by 'nacos';
mysql> grant all privileges ON nacos_config.* TO 'nacos'@'%';

#导入表结构,二选一
方法一、在浏览器输入这个地址:https://github.com/alibaba/nacos/blob/master/distribution/conf/mysql-schema.sql
从官方的网站下面复制粘贴sql脚本到数据库导入即可
方法二、下面步骤中《下载安装包并解压》的压缩包里面有.sql文件,去数据库执行.sql文件即可

下载安装包解压(3台都做一样的步骤)

wget -c https://github.com/alibaba/nacos/releases/download/2.2.2/nacos-server-2.2.2.tar.gz
tar xvf nacos-server-2.2.2.tar.gz
cd nacos/conf
[root@master conf]# ll *.sql*
-rw-r--r-- 1 502 games  1224 313 11:54 1.4.0-ipv6_support-update.sql
-rw-r--r-- 1 502 games  8939 329 15:21 derby-schema.sql			#这个不用管,我们不使用derby数据库
-rw-r--r-- 1 502 games 10825 43 16:33 mysql-schema.sql

修改配置文件,启动nacos集群

[root@master ~]# cd nacos/conf
[root@master conf]# vim application.properties			#编辑配置文件,主要是修改或取消注释下面这些参数
[root@master conf]# grep -Ev '$^|#' application.properties
server.servlet.contextPath=/nacos						#保持默认,这是URL的上下文,业务页面访问的时候需要加这个上下文
server.error.include-message=ALWAYS						#保持默认
server.port=8848										#保持默认,nacos端口
nacos.inetutils.ip-address=192.168.158.128				#nacos绑定的IP地址,不写默认监听全部地址(根据各自节点配置IP)
spring.sql.init.platform=mysql							#去掉注释,开启这个参数
db.num=1												#去掉注释,开启这个参数,数据库的数量
#填写数据库连接信息,192.168.158.131:3306是数据库的IP地址和端口,nacos_config是nacos数据库名称
db.url.0=jdbc:mysql://192.168.158.131:3306/nacos_config?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC
db.user.0=nacos											#nacos数据库的用户名,前面我们设置的用户就是nacos
db.password.0=nacos										#nacos数据库的密码,前面我们设置的nacos用户密码就是nacos				
nacos.core.auth.system.type=nacos						#保持默认
nacos.core.auth.enabled=true							#取消注释,值改为true,参数含义为是否启用nacos账号密码登录

# 这个地址https://nacos.io/zh-cn/docs/v2/guide/user/auth.html说明了认证相关的参数怎么配置
#下面这两个参数随便设置一个key/value值,官方说了在nacos-2.2.1版本之后为了安全考虑无默认值,需要自己填写
nacos.core.auth.server.identity.key=nacos
nacos.core.auth.server.identity.value=nacos

#下面这个参数官方也说了nacos-2.2.1版本之后为了安全考虑无默认值,需要自己填写
#同时,需要使用一个不少于32个字符的字符串进行base64进行加密,如 echo "bmFjb3MgaXMgdmVyeSBnb29kIHNvZnR3YXJlCg==" | base64
nacos.core.auth.plugin.nacos.token.secret.key=Ym1GamIzTWdhWE1nZG1WeWVTQm5iMjlrSUhOdlpuUjNZWEpsQ2c9PQo=
[root@master ~]# cd nacos/conf
[root@master conf]# mv cluster.conf.example cluster.conf
[root@master conf]# vim cluster.conf		#集群配置文件,填写各个节点nacos服务的IP和端口
192.168.158.128:8848
192.168.158.129:8848
192.168.158.130:8848
#cluster模式启动nacos
[root@master nacos]# cd bin/
[root@master bin]# bash startup.sh   					#启动nacos,默认模式就是cluster模式
#查看日志
tail -222f ../logs/start.out
#查看端口
lsof  -i:8848
#单独登录各个节点,看到左侧集群管理-节点列表,3个节点都是UP状态即可
#现在其实nacos已经做成cluster模式了
http://192.168.158.128:8848/nacos/index.html
http://192.168.158.129:8848/nacos/index.html
http://192.168.158.130:8848/nacos/index.html

部署nginx做slb,登录nacos

在这里插入图片描述
官网建议做SLB,这里使用nginx做slb:

#添加nginx的yum源
[root@nginx ~]# vim /etc/yum.repos.d/nginx.repo
[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true

[nginx-mainline]
name=nginx mainline repo
baseurl=http://nginx.org/packages/mainline/centos/$releasever/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true

[root@cicd cluster]# 
#安装nginx
[root@nginx ~]# yum-config-manager --enable nginx-mainline
[root@nginx ~]# yum install yum-utils
[root@nginx ~]# yum-config-manager --enable nginx-mainline
[root@nginx ~]# yum install nginx

#编写server虚拟主机文件
[root@nginx ~]# vim  /etc/nginx/conf.d/nacos.conf
upstream nacos_pools{					#下面写3个nacos服务的IP和端口
	server 192.168.158.128:8848;
	server 192.168.158.129:8848;
	server 192.168.158.130:8848;
}
server {
    listen       8848;
    server_name  nacos;
    location /nacos/{
	 	proxy_pass http://nacos_pools;		#做反向代理
     	proxy_set_header Host $host;
     	proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
	}
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

[root@nginx ~]#启动nginx服务
[root@nginx ~]#systemctl  start  nginx

#现在浏览器登录nacos,使用nginx服务器的IP+8848端口登录,验证成功
http://192.168.158.131:8848/nacos/#/login

docker部署nacos(单机模式)

克隆项目源码

git clone https://github.com/nacos-group/nacos-docker.git
cd nacos-docker
vim README.md			#查看说明
vim README_ZH.md		#查看说明
#官方文档说要启动单机模式,可以使用下面的命令进行启动(先不启动)
#单机模式 MySQL
#如果希望使用MySQL5.7(会生成两个容器,一个nacos容器,一个是mysql容器)
docker-compose -f example/standalone-mysql-5.7.yaml up
#如果希望使用MySQL8(会生成两个容器,一个nacos容器,一个是mysql容器)
docker-compose -f example/standalone-mysql-8.yaml up

查看、修改配置文件

#这里我们要使用mysql8数据库,所以我们先不启动,先看看官方的yaml文件时怎么写的
[root@master nacos-docker]# cat  example/standalone-mysql-8.yaml
version: "3.8"
services:
  nacos:
    image: nacos/nacos-server:${NACOS_VERSION}		#这个环境变量是从example/.env文件中定义的,所以有需要可以修改nacos版本
    container_name: nacos-standalone-mysql
    env_file:
      - ../env/nacos-standlone-mysql.env			#引入这个环境变量文件
    volumes:
      - ./standalone-logs/:/home/nacos/logs			#持久化数据
    ports:
      - "8848:8848"
      - "9848:9848"
    depends_on:
      mysql:
        condition: service_healthy
    restart: always
  mysql:
    container_name: mysql
    build:
      context: .
      dockerfile: ./image/mysql/8/Dockerfile
    image: example/mysql:8.0.30
    env_file:
      - ../env/mysql.env					#引入这个环境变量
    volumes:
      - ./mysql:/var/lib/mysql
    ports:
      - "3306:3306"
    healthcheck:
      test: [ "CMD", "mysqladmin" ,"ping", "-h", "localhost" ]
      interval: 5s
      timeout: 10s
      retries: 10
#查看env/nacos-standlone-mysql.env
[root@master nacos-docker]# cat env/nacos-standlone-mysql.env 	#这个nacos的环境变量
PREFER_HOST_MODE=hostname				#保持默认
MODE=standalone							#保持默认,因为我们就是要部署单机默认
SPRING_DATASOURCE_PLATFORM=mysql		#保持默认,保持默认,因为我们就是要使用mysql
MYSQL_SERVICE_HOST=mysql				#保持默认
MYSQL_SERVICE_DB_NAME=nacos_devtest		#保持默认,这是nacos的数据库名称
MYSQL_SERVICE_PORT=3306					#数据库端口,保持默认
MYSQL_SERVICE_USER=nacos				#nacos用户名称
MYSQL_SERVICE_PASSWORD=nacos			#nacos用户密码
MYSQL_SERVICE_DB_PARAM=characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useSSL=false&allowPublicKeyRetrieval=true
NACOS_AUTH_IDENTITY_KEY=nacos			#随便修改一个值,因为README_ZH.md文件说要改
NACOS_AUTH_IDENTITY_VALUE=nacos			#随便修改一个值,因为README_ZH.md文件说要改
NACOS_AUTH_TOKEN=Ym1GamIzTWdhWE1nZG1WeWVTQm5iMjlrSUhOdlpuUjNZWEpsQ2c9PQo=	#这是一个不少于32位字符串使用base64加密的秘文
SPRING_DATASOURCE_PLATFORM=mysql		#保持默认
[root@master nacos-docker]# 
#查看env/mysql.env环境变量文件内容
[root@master nacos-docker]# cat env/mysql.env 
MYSQL_ROOT_PASSWORD=root				#mysql的root账号密码
MYSQL_DATABASE=nacos_devtest			#nacos数据库的名称,跟上面文件的保持一致
MYSQL_USER=nacos						#nacos用户名称,跟上面文件的保持一致
MYSQL_PASSWORD=nacos					#nacos用户密码,跟上面文件的保持一致
LANG=C.UTF-8
[root@master nacos-docker]# 

单机模式启动nacos

#现在,直接启动即可,我们使用mysql8版本启动
docker-compose -f example/standalone-mysql-8.yaml up

#检查命令
docker ps
docker exec -it mysql  bash
#浏览器页面访问正常,登录账号密码是nacos nacos
#在页面上左侧集群管理-节点列表就能看到有一个nacos服务处于UP状态了
http://192.168.158.128:8848/nacos/

docker部署nacos(cluster模式)

克隆项目源码

git clone https://github.com/nacos-group/nacos-docker.git
cd nacos-docker
vim README.md			#查看说明
vim README_ZH.md		#查看说明

查看、修改配置文件

#可以看到,官方给出的docker部署nacos cluster模式下其实就是在一台主机上启动了3个nacos容器来实现的
[root@master nacos-docker]# cat example/cluster-hostname.yaml 
version: "3.8"
services:
  nacos1:
    hostname: nacos1
    container_name: nacos1
    image: nacos/nacos-server:${NACOS_VERSION}		#这个环境变量是从example/.env文件中定义的,所以有需要可以修改nacos版本
    volumes:
      - ./cluster-logs/nacos1:/home/nacos/logs		#持久化日志
    ports:
      - "7848:7848"
      - "8848:8848"
      - "9868:9848"
      - "9850:9849"
    env_file:
      - ../env/nacos-hostname.env					#环境变量文件
    restart: always
    depends_on:
      mysql:
        condition: service_healthy

  nacos2:
    hostname: nacos2
    image: nacos/nacos-server:${NACOS_VERSION}
    container_name: nacos2
    volumes:
      - ./cluster-logs/nacos2:/home/nacos/logs
    ports:
      - "7849:7848"
      - "8849:8848"
      - "9869:9848"
      - "9851:9849"
    env_file:
      - ../env/nacos-hostname.env
    restart: always
    depends_on:
      mysql:
        condition: service_healthy
  nacos3:
    hostname: nacos3
    image: nacos/nacos-server:${NACOS_VERSION}
    container_name: nacos3
    volumes:
      - ./cluster-logs/nacos3:/home/nacos/logs
    ports:
      - "7850:7848"
      - "8850:8848"
      - "9870:9848"
      - "9852:9849"
    env_file:
      - ../env/nacos-hostname.env
    restart: always
    depends_on:
      mysql:
        condition: service_healthy
  mysql:
    container_name: mysql
    build:
      context: .										#可以看到官网默认使用5.7版本的Dockerfile文件构建mysql5.7数据库
      dockerfile: ./image/mysql/5.7/Dockerfile			#有需要使用8.0版本的照着文件路径改下即可
    image: example/mysql:5.7							#构建的镜像名称
    env_file:
      - ../env/mysql.env
    volumes:
      - ./mysql:/var/lib/mysql							#mysql的数据持久化
    ports:
      - "3306:3306"
    healthcheck:
      test: [ "CMD", "mysqladmin" ,"ping", "-h", "localhost" ]
      interval: 5s
      timeout: 10s
      retries: 10

[root@master nacos-docker]# 
#查看环境变量nacos-hostname.env文件
[root@master nacos-docker]# cat env/nacos-hostname.env
PREFER_HOST_MODE=hostname								#保持默认
NACOS_SERVERS=nacos1:8848 nacos2:8849 nacos3:8850		#保持默认,这是3个nacos服务名称和端口
SPRING_DATASOURCE_PLATFORM=mysql						#保持默认
MYSQL_SERVICE_HOST=mysql								#保持默认
MYSQL_SERVICE_DB_NAME=nacos_devtest						#保持默认,这是nacos数据库名
MYSQL_SERVICE_PORT=3306									#保持默认,mysql端口
MYSQL_SERVICE_USER=nacos								#保持默认,nacos用户名
MYSQL_SERVICE_PASSWORD=nacos							#保持默认,nacos密码
MYSQL_SERVICE_DB_PARAM=characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useSSL=false&allowPublicKeyRetrieval=true
NACOS_AUTH_IDENTITY_KEY=nacos							#随便该一个值,这是认证相关的参数,README_ZH.md文件中说要改
NACOS_AUTH_IDENTITY_VALUE=nacos							#随便该一个值,这是认证相关的参数,README_ZH.md文件中说要改
NACOS_AUTH_TOKEN=Ym1GamIzTWdhWE1nZG1WeWVTQm5iMjlrSUhOdlpuUjNZWEpsQ2c9PQo=	#这是一个不少于32位字符串使用base64加密的秘文
SPRING_DATASOURCE_PLATFORM=mysql						#保持默认
[root@master nacos-docker]# 
#查看环境变量mysql.env文件
[root@master nacos-docker]# cat env/mysql.env 
MYSQL_ROOT_PASSWORD=root								#mysqlroot账号的密码
MYSQL_DATABASE=nacos_devtest							#nacos的数据库名称,与上面文件的保持一致即可
MYSQL_USER=nacos										#nacos的用户名称,与上面文件的保持一致即可
MYSQL_PASSWORD=nacos									#nacos用户密码,与上面文件的保持一致即可
LANG=C.UTF-8
[root@master nacos-docker]# 

cluster模式启动nacos

#现在,直接启动即可,我们使用cluster模式启动nacos
docker-compose -f example/cluster-hostname.yaml up 

#检查命令
docker ps
docker exec -it mysql  bash
#浏览器页面访问正常,登录账号密码是nacos nacos
#在页面上左侧集群管理-节点列表就能看到有3个nacos服务处于UP状态了
http://192.168.158.128:8848/nacos/
http://192.168.158.128:8849/nacos/
http://192.168.158.128:8850/nacos/

部署nginx做slb,登录nacos

在这里插入图片描述
官网建议做SLB,这里使用nginx做slb:

#添加nginx的yum源
[root@nginx ~]# vim /etc/yum.repos.d/nginx.repo
[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true

[nginx-mainline]
name=nginx mainline repo
baseurl=http://nginx.org/packages/mainline/centos/$releasever/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true

[root@cicd cluster]# 
#安装nginx
[root@nginx ~]# yum-config-manager --enable nginx-mainline
[root@nginx ~]# yum install yum-utils
[root@nginx ~]# yum-config-manager --enable nginx-mainline
[root@nginx ~]# yum install nginx

#编写server虚拟主机文件
[root@nginx ~]# vim  /etc/nginx/conf.d/nacos.conf
upstream nacos_pools{					#下面写3个nacos服务的IP和端口
	server 192.168.158.128:8848;
	server 192.168.158.128:8849;
	server 192.168.158.128:8850;
}
server {
    listen       8848;
    server_name  nacos;
    location /nacos/{
	 	proxy_pass http://nacos_pools;		#做反向代理
     	proxy_set_header Host $host;
     	proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
	}
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

[root@nginx ~]#启动nginx服务
[root@nginx ~]#systemctl  start  nginx

#现在浏览器登录nacos,使用nginx服务器的IP+8848端口登录,账号密码默认是nacos nacos,验证成功
http://192.168.158.131:8848/nacos/#/login

k8s部署nacos(单机模式)

官方提供的k8s部署nacos是属于集群模式,使用sts部署的3个pod,这里我们先使用官方的yaml改改部署单个nacos。
官方文档:https://nacos.io/zh-cn/docs/use-nacos-with-kubernetes.html

克隆项目

[root@master ~]# git clone https://github.com/nacos-group/nacos-k8s.git
[root@master ~]# cd nacos-k8s
[root@master ~]# vim README-CN.md 	#可以安装官方文档的步骤做
#
#这里由于之前已经在k8s集群里安装好了nfs存储和mysql,所以这里直接修改官方给的yaml文件进行部署nacos,不在按照官方提供的安装顺序安装。
#nfs部署参考:https://mp.csdn.net/mp_blog/creation/success/123611986
#mysql主从参考:https://blog.csdn.net/MssGuo/article/details/130261331

创建数据库、用户名、导入表结构

#我的k8s集群里面的数据库是8.0.32  
#去到mysql数据库服务器手动执行创建nacos-config数据库语句以及创建nacos用户
[root@master ~]# kubectl  exec -it mysql-primary-0 -- bash		#登录mysql的主库pod
I have no name!@mysql-primary-0:/$ mysql -uroot -p123456		#登录mysql
mysql> create database nacos_config character set utf8;			#nacos名称叫	nacos_config
mysql> create user 'nacos'@'%' identified by 'nacos';
mysql> grant all privileges ON nacos_config.* TO 'nacos'@'%';
mysql>use nacos_config;											#切换到nacos数据库
mysql> #去官网复制粘贴建表语句到这里执行即可,https://github.com/alibaba/nacos/blob/develop/distribution/conf/mysql-schema.sql

修改yaml文件

[root@master ~]#  cd nacos-k8s/deploy/nacos
[root@master nacos]# cp nacos-pvc-nfs.yaml  nacos-single.yaml			#从官方的yaml复制一份,修改为自己的yaml
[root@master nacos]# vim nacos-single.yaml
---
apiVersion: v1						#定义一个NodePort类型的svc,用于外部访问
kind: Service
metadata:
  name: nacos-svc
  labels:
    app: nacos
spec:
  ports:
    - port: 8848
      name: server
      targetPort: 8848
      nodePort: 8848
  type: NodePort
  selector:
    app: nacos
---
apiVersion: v1
kind: Service						#定义一个无头svc,供sts使用
metadata:
  name: nacos-headless
  labels:
    app: nacos
spec:
  publishNotReadyAddresses: true 
  ports:
    - port: 8848
      name: server
      targetPort: 8848
  clusterIP: None
  selector:
    app: nacos
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: nacos-cm
data:
  mysql.host: "mysql-primary-headless.default.svc.cluster.local"	#这里填写mysql的主机名,mysql的svc域名
  mysql.db.name: "nacos_config"			#nacos的数据库,这个数据库要提前在mysql里面创建
  mysql.port: "3306"					#数据库端口,mysql的svc的端口
  mysql.user: "nacos"					#nacos用户名
  mysql.password: "nacos"				#nacos用户密码
---
apiVersion: apps/v1						#定义sts
kind: StatefulSet
metadata:
  name: nacos
spec:
  serviceName: nacos-headless
  replicas: 1							#副本数1 
  template:
    metadata:
      labels:
        app: nacos
      annotations:
        pod.alpha.kubernetes.io/initialized: "true"
    spec:
      affinity:
        podAntiAffinity:											#pod反亲和性
          requiredDuringSchedulingIgnoredDuringExecution:
            - labelSelector:
                matchExpressions:
                  - key: "app"
                    operator: In
                    values:
                      - nacos
              topologyKey: "kubernetes.io/hostname"		#拓扑域
      containers:
        - name: nacos
          imagePullPolicy: Always
          image: nacos/nacos-server:v2.3.1		#nacos镜像
          resources:
            requests:
              memory: "1Gi"						#资源请求,最少1G,改小了pod启动不了,因为镜像里面jvm设置启动参数就是1G
              cpu: "800m"
          ports:
            - containerPort: 8848
              name: client-port
          env:
            - name: NACOS_AUTH_ENABLE			# 开启认证
              value: "true"
            - name: NACOS_AUTH_TOKEN		
              value: "Ym1GamIzTWdhWE1nZG1WeWVTQm5iMjlrSUhOdlpuUjNZWEpsQ2c9PQo="	#这是一个不少于32位字符串使用base64加密秘文
            - name: NACOS_AUTH_IDENTITY_KEY		
              value: "nacos"
            - name: NACOS_AUTH_IDENTITY_VALUE
              value: "nacos" 
            - name: MODE						#指定nacos以单机模式启动,默认是以cluster模式启动的
              value: "standalone"											
            - name: NACOS_REPLICAS
              value: "1"
            - name: SERVICE_NAME
              value: "nacos-headless"
            - name: DOMAIN_NAME
              value: "cluster.local"
            - name: POD_NAMESPACE
              valueFrom:
                fieldRef:
                  apiVersion: v1
                  fieldPath: metadata.namespace
            - name: MYSQL_SERVICE_HOST
              valueFrom:
                configMapKeyRef:
                  name: nacos-cm
                  key: mysql.host
            - name: MYSQL_SERVICE_DB_NAME
              valueFrom:
                configMapKeyRef:
                  name: nacos-cm
                  key: mysql.db.name
            - name: MYSQL_SERVICE_PORT
              valueFrom:
                configMapKeyRef:
                  name: nacos-cm
                  key: mysql.port
            - name: MYSQL_SERVICE_USER
              valueFrom:
                configMapKeyRef:
                  name: nacos-cm
                  key: mysql.user
            - name: MYSQL_SERVICE_PASSWORD
              valueFrom:
                configMapKeyRef:
                  name: nacos-cm
                  key: mysql.password
            - name: SPRING_DATASOURCE_PLATFORM
              value: "mysql"
            - name: NACOS_SERVER_PORT
              value: "8848"
            - name: NACOS_APPLICATION_PORT
              value: "8848"
          volumeMounts:
            - name: data
              mountPath: /home/nacos/data
              subPath: data
            - name: data
              mountPath: /home/nacos/logs
              subPath: logs
  volumeClaimTemplates:
    - metadata:
        name: data
        annotations:
          volume.beta.kubernetes.io/storage-class: "nfs-storageclass"	#定义存储类
      spec:
        accessModes: [ "ReadWriteMany" ]
        resources:
          requests:
            storage: 1Gi												#pv大小
  selector:	
    matchLabels:
      app: nacos
[root@master nacos]# 

启动nacos

[root@master nacos]#  kubectl apply -f nacos-single.yaml
#nacos里面的配置文件application.properties,该配置文件里面启动定义了很多环境变量的参数,如果你想要修改某些环境变量的参数,可以在
#StatefulSet定义环境变量,由环境变量注入到pod里面成为pod的环境变量,然后application.properties文件就能使用这些环境变量了,
# application.properties文件里面官方写的配置都是正确的。
[root@master nacos]# kubectl  exec -it nacos-0 -- ls conf/
1.4.0-ipv6_support-update.sql  nacos-logback.xml
application.properties	       schema.sql
[root@master nacos]# 
页面登录:默认账号密码是nacos/nacos
http://192.168.158.128:8848/nacos/#/login
左侧集群管理-节点列表显示1个节点状态正常

问题排查

#如果nacos在启动时报错,比如No DataSource set,这时必须确保数据库的地址、数据库名称、端口是正确的,就是核对定义nacos-cm这个
#configmap的key的值是正确的,千万要核对一遍。因为笔者没有好好核对数据库名称,导致去nacos pod里面查看配置文件application.properties
#时,看到官方写的:
db.url.0=jdbc:mysql://${MYSQL_SERVICE_HOST}:${MYSQL_SERVICE_PORT:3306}/${MYSQL_SERVICE_DB_NAME}?${MYSQL_SERVICE_DB_PARAM:characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useSSL=false}
#一直觉得人家写的有问题,因为尝试echo ${MYSQL_SERVICE_PORT:3306} 得到的是空值,即使echo ${db.url.0}得到的url也是存在问题,所以就
#一直觉得人家官方写的有问题,其实不是的,最终发现是我的configmap里面的mysql.db.name这个可以定义的值和mysql数据库里面的nacos库名对不
#上。靠,最后改了nacos pod就可以正常启动了,页面访问也正常。	

挂载配置文件到pod里面

使用下面这种方式,自定义配置文件,部署nacos单机模式也是可以:

[root@master nacos-k8s-single]# cat nacos-single-custom-configmap.yaml 
# 请阅读Wiki文章
# https://github.com/nacos-group/nacos-k8s/wiki/%E4%BD%BF%E7%94%A8peerfinder%E6%89%A9%E5%AE%B9%E6%8F%92%E4%BB%B6
---
apiVersion: v1
kind: Service
metadata:
  name: nacos-svc
  labels:
    app: nacos
spec:
  ports:
    - port: 8848
      name: server
      targetPort: 8848
      nodePort: 8848
  type: NodePort
  selector:
    app: nacos
---
apiVersion: v1
kind: Service
metadata:
  name: nacos-headless
  labels:
    app: nacos
spec:
  publishNotReadyAddresses: true
  ports:
    - port: 8848
      name: server
      targetPort: 8848
  clusterIP: None
  selector:
    app: nacos
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: nacos-cm
data:
  mysql.host: "mysql-primary-headless.default.svc.cluster.local"
  mysql.db.name: "nacos_config"
  mysql.port: "3306"
  mysql.user: "nacos"
  mysql.password: "nacos"
  application.properties: |					#加多了这个key
    # spring
    server.servlet.contextPath=/nacos
    server.contextPath=/nacos
    server.port=8848
    spring.datasource.platform=mysql
    nacos.cmdb.dumpTaskInterval=3600
    nacos.cmdb.eventTaskInterval=10
    nacos.cmdb.labelTaskInterval=300
    nacos.cmdb.loadDataAtStart=false
    db.num=1
    db.url.0=jdbc:mysql://${MYSQL_SERVICE_HOST}:${MYSQL_SERVICE_PORT}/${MYSQL_SERVICE_DB_NAME}?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&&serverTimezone=UTC
    db.url.1=jdbc:mysql://${MYSQL_SERVICE_HOST}:${MYSQL_SERVICE_PORT}/${MYSQL_SERVICE_DB_NAME}?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC
    db.user=${MYSQL_SERVICE_USER}
    db.password=${MYSQL_SERVICE_PASSWORD}
    # ### The auth system to use, currently only 'nacos' is supported:
    nacos.core.auth.system.type=nacos
    #
    #
    # ### The token expiration in seconds:
    nacos.core.auth.default.token.expire.seconds=18000
    #
    # ### The default token:
    nacos.core.auth.default.token.secret.key=Ym1GamIzTWdhWE1nZG1WeWVTQm5iMjlrSUhOdlpuUjNZWEpsQ2c9PQo=
    #
    # ### 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=false
    nacos.core.auth.enable.userAgentAuthWhite=false
    nacos.core.auth.server.identity.key=nacos
    nacos.core.auth.server.identity.value=nacos
    server.tomcat.accesslog.enabled=false
    server.tomcat.accesslog.pattern=%h %l %u %t "%r" %s %b %D
    # # default current work dir
    server.tomcat.basedir=
    # ## spring security config
    # ### turn off security
    nacos.security.ignore.urls=/,/error,/**/*.css,/**/*.js,/**/*.html,/**/*.map,/**/*.svg,/**/*.png,/**/*.ico,/console-fe/public/**,/v1/auth/**,/v1/console/health/**,/actuator/**,/v1/console/server/**
    # # metrics for elastic search
    management.metrics.export.elastic.enabled=false
    management.metrics.export.influx.enabled=false
    
    nacos.naming.distro.taskDispatchThreadCount=10
    nacos.naming.distro.taskDispatchPeriod=200
    nacos.naming.distro.batchSyncKeyCount=1000
    nacos.naming.distro.initDataRatio=0.9
    nacos.naming.distro.syncRetryDelay=5000
    nacos.naming.data.warmup=true
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: nacos
spec:
  serviceName: nacos-headless
  replicas: 1
  template:
    metadata:
      labels:
        app: nacos
      annotations:
        pod.alpha.kubernetes.io/initialized: "true"
    spec:
      affinity:
        podAntiAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
            - labelSelector:
                matchExpressions:
                  - key: "app"
                    operator: In
                    values:
                      - nacos
              topologyKey: "kubernetes.io/hostname"
      volumes:
      - name: nacos-cm
        configMap:
          name: nacos-cm
          items:
          - key: application.properties
            path: application.properties
      containers:
        - name: nacos
          imagePullPolicy: Always
          image: nacos/nacos-server:latest
          resources:
            requests:
              memory: "1Gi"
              cpu: "800m"
          ports:
            - containerPort: 8848
              name: client-port
          env:
            - name: MODE
              value: "standalone"
            - name: NACOS_REPLICAS
              value: "1"
            - name: SERVICE_NAME
              value: "nacos-headless"
            - name: DOMAIN_NAME
              value: "cluster.local"
            - name: POD_NAMESPACE
              valueFrom:
                fieldRef:
                  apiVersion: v1
                  fieldPath: metadata.namespace
            - name: MYSQL_SERVICE_HOST
              valueFrom:
                configMapKeyRef:
                  name: nacos-cm
                  key: mysql.host
            - name: MYSQL_SERVICE_DB_NAME
              valueFrom:
                configMapKeyRef:
                  name: nacos-cm
                  key: mysql.db.name
            - name: MYSQL_SERVICE_PORT
              valueFrom:
                configMapKeyRef:
                  name: nacos-cm
                  key: mysql.port
            - name: MYSQL_SERVICE_USER
              valueFrom:
                configMapKeyRef:
                  name: nacos-cm
                  key: mysql.user
            - name: MYSQL_SERVICE_PASSWORD
              valueFrom:
                configMapKeyRef:
                  name: nacos-cm
                  key: mysql.password
          volumeMounts:
            - name: data
              mountPath: /home/nacos/data
              subPath: data
            - name: data
              mountPath: /home/nacos/logs
              subPath: logs
            - name: nacos-cm
              mountPath: /home/nacos/conf/application.properties
              subPath: application.properties
  volumeClaimTemplates:
    - metadata:
        name: data
        annotations:
          volume.beta.kubernetes.io/storage-class: "nfs-storageclass"
      spec:
        accessModes: [ "ReadWriteMany" ]
        resources:
          requests:
            storage: 1Gi
  selector:
    matchLabels:
      app: nacos
[root@master nacos-k8s-single]# 

k8s部署nacos(cluster模式)

官方提供的k8s部署nacos是属于集群模式,使用sts部署的3个pod。
官方文档:https://nacos.io/zh-cn/docs/use-nacos-with-kubernetes.html

克隆项目

[root@master ~]# git clone https://github.com/nacos-group/nacos-k8s.git
[root@master ~]# cd nacos-k8s
[root@master ~]# vim README-CN.md 	#可以安装官方文档的步骤做
#
#这里由于之前已经在k8s集群里安装好了nfs存储和mysql,所以这里直接修改官方给的yaml文件进行部署cluster 模式的nacos,不在按照官方提供的安装顺序安装。
#nfs部署参考:https://mp.csdn.net/mp_blog/creation/success/123611986
#mysql主从参考:https://blog.csdn.net/MssGuo/article/details/130261331

创建数据库、用户名、导入表结构

#我的k8s集群里面的数据库是8.0.32  
#去到mysql数据库服务器手动执行创建nacos-config数据库语句以及创建nacos用户
[root@master ~]# kubectl  exec -it mysql-primary-0 -- bash		#登录mysql的主库pod
I have no name!@mysql-primary-0:/$ mysql -uroot -p123456		#登录mysql
mysql> create database nacos_config character set utf8;			#nacos名称叫	nacos_config
mysql> create user 'nacos'@'%' identified by 'nacos';
mysql> grant all privileges ON nacos_config.* TO 'nacos'@'%';
mysql>use nacos_config;											#切换到nacos数据库
mysql> #去官网复制粘贴建表语句到这里执行即可,https://github.com/alibaba/nacos/blob/develop/distribution/conf/mysql-schema.sql

修改yaml文件

#这里由于之前已经在k8s集群里安装好了nfs存储和mysql,所以这里直接修改官方给的yaml文件进行部署cluster 模式的nacos,不在按照官方提供的安装顺序安装。
[root@master ~]# cd nacos-k8s/deploy/nacos
[root@master nacos]# vim nacos-pvc-nfs.yaml 
# 请阅读Wiki文章
# https://github.com/nacos-group/nacos-k8s/wiki/%E4%BD%BF%E7%94%A8peerfinder%E6%89%A9%E5%AE%B9%E6%8F%92%E4%BB%B6
---
#自己添加的nodePort类型的service,原来官方文档只有无头svc
apiVersion: v1
kind: Service
metadata:
  name: nacos-svc
  labels:
    app: nacos
spec:
  ports:
    - port: 8848
      name: server
      targetPort: 8848
      nodePort: 8848
  type: NodePort
  selector:
    app: nacos
---
apiVersion: v1
kind: Service
metadata:
  name: nacos-headless
  labels:
    app: nacos
spec:
  publishNotReadyAddresses: true 
  ports:
    - port: 8848
      name: server
      targetPort: 8848
    - port: 9848
      name: client-rpc
      targetPort: 9848
    - port: 9849
      name: raft-rpc
      targetPort: 9849
    ## 兼容1.4.x版本的选举端口
    - port: 7848
      name: old-raft-rpc
      targetPort: 7848
  clusterIP: None
  selector:
    app: nacos
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: nacos-cm
data:
  mysql.host: "mysql-primary-headless.default.svc.cluster.local"       #修改为k8s集群内mysql主库的svc地址
  mysql.db.name: "nacos_config"                                        #nacos的数据库名,这个数据库需要提前创建好,并导入数据
  mysql.port: "3306"                                                   #数据库端口
  mysql.user: "nacos"                                                  #mysql的nacos用户
  mysql.password: "nacos"                                              #mysql的nacos用户密码
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: nacos
spec:
  podManagementPolicy: Parallel
  serviceName: nacos-headless
  replicas: 3
  template:
    metadata:
      labels:
        app: nacos
      annotations:
        pod.alpha.kubernetes.io/initialized: "true"
    spec:
      affinity:
        podAntiAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
            - labelSelector:
                matchExpressions:
                  - key: "app"
                    operator: In
                    values:
                      - nacos
              topologyKey: "kubernetes.io/hostname"
      serviceAccountName: nfs-client-provisioner
      initContainers:
        - name: peer-finder-plugin-install
          image: nacos/nacos-peer-finder-plugin:1.1
          imagePullPolicy: Always
          volumeMounts:
            - mountPath: /home/nacos/plugins/peer-finder
              name: data
              subPath: peer-finder
      containers:
        - name: nacos
          imagePullPolicy: Always
          image: nacos/nacos-server:latest
          resources:
            requests:
              memory: "1Gi"       #内存申请,官方建议2Gi,最少1Gi,因为镜像里面定义的jvm参数就是1g,否则pod启动失败
              cpu: "500m"
          ports:
            - containerPort: 8848
              name: client-port
            - containerPort: 9848
              name: client-rpc
            - containerPort: 9849
              name: raft-rpc
            - containerPort: 7848
              name: old-raft-rpc
          env:
            - name: NACOS_REPLICAS
              value: "3"
            - name: SERVICE_NAME
              value: "nacos-headless"
            - name: DOMAIN_NAME
              value: "cluster.local"
            - name: POD_NAMESPACE
              valueFrom:
                fieldRef:
                  apiVersion: v1
                  fieldPath: metadata.namespace
            - name: MYSQL_SERVICE_HOST
              valueFrom:
                configMapKeyRef:
                  name: nacos-cm
                  key: mysql.host
            - name: MYSQL_SERVICE_DB_NAME
              valueFrom:
                configMapKeyRef:
                  name: nacos-cm
                  key: mysql.db.name
            - name: MYSQL_SERVICE_PORT
              valueFrom:
                configMapKeyRef:
                  name: nacos-cm
                  key: mysql.port
            - name: MYSQL_SERVICE_USER
              valueFrom:
                configMapKeyRef:
                  name: nacos-cm
                  key: mysql.user
            - name: MYSQL_SERVICE_PASSWORD
              valueFrom:
                configMapKeyRef:
                  name: nacos-cm
                  key: mysql.password
            - name: SPRING_DATASOURCE_PLATFORM
              value: "mysql"
            - name: NACOS_SERVER_PORT
              value: "8848"
            - name: NACOS_APPLICATION_PORT
              value: "8848"
            - name: PREFER_HOST_MODE
              value: "hostname"
          volumeMounts:
            - name: data
              mountPath: /home/nacos/plugins/peer-finder
              subPath: peer-finder
            - name: data
              mountPath: /home/nacos/data
              subPath: data
            - name: data
              mountPath: /home/nacos/logs
              subPath: logs
  volumeClaimTemplates:
    - metadata:
        name: data
        annotations:
          volume.beta.kubernetes.io/storage-class: "nfs-storageclass"   #存储类
      spec:
        accessModes: [ "ReadWriteMany" ]
        resources:
          requests:
            storage: 1Gi                                                #pv大小,官方建议20Gi
  selector:
    matchLabels:
      app: nacos
[root@master nacos]# 
#从上面可以看的出来,官方其实是使用一个叫peer-finder的插件初始化容器做到nacos节点组成集群的

启动nacos

[root@master nacos]# kubectl  apply  -f nacos-pvc-nfs.yaml
[root@master nacos]# kubectl  get pod -l app=nacos
NAME      READY   STATUS    RESTARTS   AGE
nacos-0   1/1     Running   0          14m
nacos-1   1/1     Running   0          14m
nacos-2   1/1     Running   0          14m
[root@master nacos]# 
页面登录:默认账号密码是nacos/nacos
http://192.168.158.128:8848/nacos/#/login
左侧集群管理-节点列表显示3个节点状态正常

k8s helm 部署nacos(单机模式)

克隆项目

[root@master ~]# git clone https://github.com/nacos-group/nacos-k8s.git
[root@master ~]# cd nacos-k8s
[root@master ~]# vim README-CN.md 	#可以安装官方文档的步骤做
#
#这里由于之前已经在k8s集群里安装好了nfs存储和mysql,所以这里直接修改官方给的yaml文件进行部署nacos,不在按照官方提供的安装顺序安装。
#nfs部署参考:https://mp.csdn.net/mp_blog/creation/success/123611986
#mysql主从参考:https://blog.csdn.net/MssGuo/article/details/130261331

创建数据库、用户名、导入表结构

#我的k8s集群里面的数据库是8.0.32  
#去到mysql数据库服务器手动执行创建nacos-config数据库语句以及创建nacos用户
[root@master ~]# kubectl  exec -it mysql-primary-0 -- bash		#登录mysql的主库pod
I have no name!@mysql-primary-0:/$ mysql -uroot -p123456		#登录mysql
mysql> create database nacos_config character set utf8;			#nacos名称叫	nacos_config
mysql> create user 'nacos'@'%' identified by 'nacos';
mysql> grant all privileges ON nacos_config.* TO 'nacos'@'%';
mysql>use nacos_config;											#切换到nacos数据库
mysql> #去官网复制粘贴建表语句到这里执行即可,https://github.com/alibaba/nacos/blob/develop/distribution/conf/mysql-schema.sql

修改helm的values.yaml文件

官方给的helm文件。默认就是部署单机版本的nacos。

[root@master helm]# cd nacos-k8s/helm/
[root@master helm]# vim values.yaml 		#编辑values.yaml文件
# Default values for nacos.
# This is a YAML-formatted file.
# Declare variables to be passed into your templates.

global:
  mode: standalone							#默认就是部署单机版本的nacos
#  mode: cluster

############################nacos###########################
namespace: default
nacos:
  image:
    repository: nacos/nacos-server
    tag: latest
    pullPolicy: IfNotPresent
  plugin:
    enable: true
    image:
      repository: nacos/nacos-peer-finder-plugin
      tag: 1.1
      pullPolicy: IfNotPresent
  replicaCount: 1
  podManagementPolicy: Parallel
  domainName: cluster.local
  preferhostmode: hostname
  serverPort: 8848
  health:
    enabled: false
  storage:
#    type: embedded						#注释掉这行,启用下面的mysql参数
    type: mysql
    db:
      host: mysql-primary-headless.default.svc.cluster.local		#k8s集群内的mysql svc地址
      name: nacos_config				#nacos的数据库,就是上面我们创建的数据库
      port: 3306						#mysql端口
      username: nacos					#mysql数据库里面nacos用户名
      password: nacos					#mysql数据库里面nacos用户密码
      param: characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useSSL=false

persistence:
  enabled: true							#开启持久化
  data:
    accessModes:
      - ReadWriteOnce
    storageClassName: nfs-storageclass	#指定存储类
    resources:
      requests:
        storage: 1Gi					#pv大小


service:								#svc的类型,官方默认就是NodePort,因为就单机版nacos,所以就保持默认吧
  #type: ClusterIP
  type: NodePort
  port: 8848
  nodePort: 30000


ingress:
  enabled: false
  # apiVersion: extensions/v1beta1
  apiVersion: networking.k8s.io/v1
  annotations: { }
    # kubernetes.io/ingress.class: nginx
    # kubernetes.io/tls-acme: "true"
    # For Kubernetes >= 1.18 you should specify the ingress-controller via the field ingressClassName
    # See https://kubernetes.io/blog/2020/04/02/improvements-to-the-ingress-api-in-kubernetes-1.18/#specifying-the-class-of-an-ingress
    # ingressClassName: nginx
  ingressClassName: "nginx"
  hosts:
    - host: nacos.example.com
      #paths: [ ]

  tls: [ ]
  #  - secretName: chart-example-tls
  #    hosts:
  #      - chart-example.local

resources:
  # We usually recommend not to specify default resources and to leave this as a conscious
  # choice for the user. This also increases chances charts run on environments with little
  # resources, such as Minikube. If you do want to specify resources, uncomment the following
  # lines, adjust them as necessary, and remove the curly braces after 'resources:'.
  # limits:
  #   cpu: 100m
  #   memory: 128Mi
  requests:
    cpu: 500m	
    memory: 1Gi				#资源请求,最少1G,官方默认2G,镜像里面的jvm参数定义了1G,所以设为1G才能正常启动pod
annotations: { }

nodeSelector: { }

tolerations: [ ]

affinity: { }

[root@master helm]# 

helm启动nacos

[root@master helm]# cd ../
[root@master nacos-k8s]# helm  install  nacos nacos-k8s/
[root@master nacos-k8s]# kubectl get pod -l app=nacos
[root@master nacos-k8s]# kubectl get svc		
#查看svc的nodePort的端口,页面访问,账号密码是nacos/nacos
访问地址:http://192.168.158.128:30254/nacos/#/login

k8s helm 部署nacos(cluster模式)

克隆项目

[root@master ~]# git clone https://github.com/nacos-group/nacos-k8s.git
[root@master ~]# cd nacos-k8s
[root@master ~]# vim README-CN.md 	#可以安装官方文档的步骤做
#
#这里由于之前已经在k8s集群里安装好了nfs存储和mysql,所以这里直接修改官方给的yaml文件进行部署nacos,不在按照官方提供的安装顺序安装。
#nfs部署参考:https://mp.csdn.net/mp_blog/creation/success/123611986
#mysql主从参考:https://blog.csdn.net/MssGuo/article/details/130261331

创建数据库、用户名、导入表结构

#我的k8s集群里面的数据库是8.0.32  
#去到mysql数据库服务器手动执行创建nacos-config数据库语句以及创建nacos用户
[root@master ~]# kubectl  exec -it mysql-primary-0 -- bash		#登录mysql的主库pod
I have no name!@mysql-primary-0:/$ mysql -uroot -p123456		#登录mysql
mysql> create database nacos_config character set utf8;			#nacos名称叫	nacos_config
mysql> create user 'nacos'@'%' identified by 'nacos';
mysql> grant all privileges ON nacos_config.* TO 'nacos'@'%';
mysql>use nacos_config;											#切换到nacos数据库
mysql> #去官网复制粘贴建表语句到这里执行即可,https://github.com/alibaba/nacos/blob/develop/distribution/conf/mysql-schema.sql

修改helm的values.yaml文件

[root@master ~ ]# cd nacos-k8s/helm
[root@master helm ]# vim values.yaml
# Default values for nacos.
# This is a YAML-formatted file.
# Declare variables to be passed into your templates.

global:
#  mode: standalone
  mode: cluster

############################nacos###########################
namespace: default
nacos:
  image:
    repository: nacos/nacos-server
    tag: latest
    pullPolicy: IfNotPresent
  plugin:
    enable: true
    image:
      repository: nacos/nacos-peer-finder-plugin
      tag: 1.1
      pullPolicy: IfNotPresent
  replicaCount: 3
  podManagementPolicy: Parallel
  domainName: cluster.local
  preferhostmode: hostname
  serverPort: 8848
  health:
    enabled: false
  storage:
#    type: embedded
    type: mysql
    db:
      host: mysql-primary-headless.default.svc.cluster.local	#k8s集权内部mysql的svc地址
      name: nacos_config										#nacos的数据库名
      port: 3306												#数据库端口
      username: nacos											#数据库nacos用户名
      password: nacos											#数据库nacos用户密码
      param: characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useSSL=false

persistence:
  enabled: true								#开启持久化
  data:
    accessModes:
      - ReadWriteOnce
    storageClassName: nfs-storageclass		#存储类
    resources:
      requests:
        storage: 1Gi		#pv大小,自己改


service:
#  type: ClusterIP
  type: NodePort			#这个改为NodePort类型,暴露nacos外部访问
  port: 8848
  nodePort: 8848			#这个指定的端口并不是外部访问nacos的端口,看template/service.yaml就指定了


ingress:
  enabled: false
  # apiVersion: extensions/v1beta1
  apiVersion: networking.k8s.io/v1
  annotations: { }
    # kubernetes.io/ingress.class: nginx
    # kubernetes.io/tls-acme: "true"
    # For Kubernetes >= 1.18 you should specify the ingress-controller via the field ingressClassName
    # See https://kubernetes.io/blog/2020/04/02/improvements-to-the-ingress-api-in-kubernetes-1.18/#specifying-the-class-of-an-ingress
    # ingressClassName: nginx
  ingressClassName: "nginx"
  hosts:
    - host: nacos.example.com
      #paths: [ ]

  tls: [ ]
  #  - secretName: chart-example-tls
  #    hosts:
  #      - chart-example.local

resources:
  # We usually recommend not to specify default resources and to leave this as a conscious
  # choice for the user. This also increases chances charts run on environments with little
  # resources, such as Minikube. If you do want to specify resources, uncomment the following
  # lines, adjust them as necessary, and remove the curly braces after 'resources:'.
  # limits:
  #   cpu: 100m
  #   memory: 128Mi
  requests:
    cpu: 500m
    memory: 1Gi
annotations: { }

nodeSelector: { }

tolerations: [ ]

affinity: { }
[root@master helm]# 

helm启动nacos

[root@master helm]# cd ../
[root@master nacos-k8s]# helm  install  nacos nacos-k8s/
[root@master nacos-k8s]# kubectl get pod | grep nacos
[root@master nacos-k8s]# kubectl get svc		
#查看svc的nodePort的端口,页面访问,账号密码是nacos/nacos
访问地址:http://192.168.158.128:30254/nacos/#/login

以上讲解了多种方式安装nacos,根据自己的需求任选一种部署即可。

Logo

K8S/Kubernetes社区为您提供最前沿的新闻资讯和知识内容

更多推荐