Install nacos in docker, very detailed

Install nacos in docker, very detailed


I thought that installing nacos in the Linux docker would be a little more troublesome than in the window, but it would not be too much trouble. It turns out that I was thinking too much, and I still stepped on a lot of pitfalls during the installation process. Here is a record.

1. Install docker

The prerequisite for installing nacos in docker is to have docker, if not, please Baidu yourself.

2. Pull the nacos image

Those who are anxious can just watch 2 or 3 directly.

1. Check the nacos images

The query command is as follows:

docker search nacos

insert image description here
Generally, if there is no special requirement, choose the first one, and the first one is the one with the highest start.

2. Obtain the latest version of the image

Directly use docker pull + "NAME" to pull the latest version of the image, the command is as follows:

docker pull nacos/nacos-server

insert image description here
latest represents the latest version.

3. Obtain the specified version of the image

Using docker pull + "NAME: version number" is to get the image of the specified version. I got the version of nacos2.2.1. The command is as follows:

docker pull nacos/nacos-server:v2.2.1

insert image description here

4. View the local mirror

The command is as follows:

docker images

insert image description here
You can see the two images downloaded earlier.

5. Delete the mirror image

I want to use the nacos2.2.1 version of the mirror, use docker rmi -f + "mirror id" to delete the latest version, the delete command is as follows:

docker rmi -f f151dab7a111

insert image description here
insert image description here
You can see that the mirror image of the latest version of nacos has been deleted.

3. Create a mount directory

The mounted directory is used to operate the configuration files, logs, and data files in the nacos image on the host. That is, the command to create a multi-level file.

1. Create a nacos configuration file mounting directory

It is used to mount the files in the /home/nacos/conf/ directory in the nacos image later, this is mine:

mkdir -p /www/wwwroot/changjing/docker/nacos/conf

The function of -p is to create a multi-level file, if a certain level file does not exist, it will be created, and if it exists, the original file will be used

insert image description here

2. Create a nacos log file mounting directory

It is used to mount the files in the /home/nacos/logs/ directory in the nacos image later, this is mine:

mkdir -p /www/wwwroot/changjing/docker/nacos/logs

insert image description here

3. Create a nacos data file mounting directory

It is used to mount the files in the /home/nacos/data/ directory in the nacos image later, this is mine:

mkdir -p /www/wwwroot/changjing/docker/nacos/data

insert image description here

4. Start nacos, copy relevant files to the mount directory

You need to start the nacos image to create a container before you can copy the relevant files in the container to the mount directory.

1. Start the nacos container

This is simply enabled to copy the relevant files of the nacos container to the mount directory

docker run --name nacos -d -p 8848:8848 -e MODE=standalone  nacos/nacos-server:v2.2.1

explain:

docker run -d : Start the container, -d means to start in the background and return the container id –name
nacos : The name of the container is nacos
-p 8848:8848 : The port number related to the container, before ":" is the host access to start the container port number, " :" followed by the container port number
-e MODE=standalone: ​​start
nacos/nacos-server:v2.2.1 in a stand-alone version: start the nacos image of the container

insert image description here

2. Copy the relevant files of the container to the mount directory

Use docker cp "container name": "container-related file directory" "host file directory" to copy container-related files to the host

(1), copy the container configuration file to the host

docker cp nacos:/home/nacos/conf/ /www/wwwroot/changjing/docker/nacos

Notice:

My local file here does not add conf, if it is added, another conf will be created under conf, and the same reason behind.

insert image description here
You can see that the configuration file in the container has been copied to the host.

(2), copy the container log file to the host

docker cp nacos:/home/nacos/logs/ /www/wwwroot/changjing/docker/nacos

insert image description here

(3), copy the container data file to the host

docker cp nacos:/home/nacos/data/ /www/wwwroot/changjing/docker/nacos

insert image description here

5. Modify nacos to store information in mysql

There is already a mysql database by default here, and there is no Baidu installation by itself.

1. Import the nacos related database into the mysql of the host machine

(1), create a database

Direct import has no effect, the database needs to be created first, and the database name can be customized. This is my creation command:

CREATE DATABASE `cj-config`

(2), database script

The database script was copied to the configuration file of the host machine earlier,
insert image description here
as follows:

CREATE TABLE `config_info` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `data_id` varchar(255) NOT NULL COMMENT 'data_id',
  `group_id` varchar(128) DEFAULT NULL,
  `content` longtext NOT NULL COMMENT 'content',
  `md5` varchar(32) DEFAULT NULL COMMENT 'md5',
  `gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间',
  `src_user` text COMMENT 'source user',
  `src_ip` varchar(50) DEFAULT NULL COMMENT 'source ip',
  `app_name` varchar(128) DEFAULT NULL,
  `tenant_id` varchar(128) DEFAULT '' COMMENT '租户字段',
  `c_desc` varchar(256) DEFAULT NULL,
  `c_use` varchar(64) DEFAULT NULL,
  `effect` varchar(64) DEFAULT NULL,
  `type` varchar(64) DEFAULT NULL,
  `c_schema` text,
  `encrypted_data_key` text NOT NULL COMMENT '秘钥',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_configinfo_datagrouptenant` (`data_id`,`group_id`,`tenant_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='config_info';

/******************************************/
/*   数据库全名 = nacos_config   */
/*   表名称 = config_info_aggr   */
/******************************************/
CREATE TABLE `config_info_aggr` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `data_id` varchar(255) NOT NULL COMMENT 'data_id',
  `group_id` varchar(128) NOT NULL COMMENT 'group_id',
  `datum_id` varchar(255) NOT NULL COMMENT 'datum_id',
  `content` longtext NOT NULL COMMENT '内容',
  `gmt_modified` datetime NOT NULL COMMENT '修改时间',
  `app_name` varchar(128) DEFAULT NULL,
  `tenant_id` varchar(128) DEFAULT '' COMMENT '租户字段',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_configinfoaggr_datagrouptenantdatum` (`data_id`,`group_id`,`tenant_id`,`datum_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='增加租户字段';


/******************************************/
/*   数据库全名 = nacos_config   */
/*   表名称 = config_info_beta   */
/******************************************/
CREATE TABLE `config_info_beta` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `data_id` varchar(255) NOT NULL COMMENT 'data_id',
  `group_id` varchar(128) NOT NULL COMMENT 'group_id',
  `app_name` varchar(128) DEFAULT NULL COMMENT 'app_name',
  `content` longtext NOT NULL COMMENT 'content',
  `beta_ips` varchar(1024) DEFAULT NULL COMMENT 'betaIps',
  `md5` varchar(32) DEFAULT NULL COMMENT 'md5',
  `gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间',
  `src_user` text COMMENT 'source user',
  `src_ip` varchar(50) DEFAULT NULL COMMENT 'source ip',
  `tenant_id` varchar(128) DEFAULT '' COMMENT '租户字段',
  `encrypted_data_key` text NOT NULL COMMENT '秘钥',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_configinfobeta_datagrouptenant` (`data_id`,`group_id`,`tenant_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='config_info_beta';

/******************************************/
/*   数据库全名 = nacos_config   */
/*   表名称 = config_info_tag   */
/******************************************/
CREATE TABLE `config_info_tag` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `data_id` varchar(255) NOT NULL COMMENT 'data_id',
  `group_id` varchar(128) NOT NULL COMMENT 'group_id',
  `tenant_id` varchar(128) DEFAULT '' COMMENT 'tenant_id',
  `tag_id` varchar(128) NOT NULL COMMENT 'tag_id',
  `app_name` varchar(128) DEFAULT NULL COMMENT 'app_name',
  `content` longtext NOT NULL COMMENT 'content',
  `md5` varchar(32) DEFAULT NULL COMMENT 'md5',
  `gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间',
  `src_user` text COMMENT 'source user',
  `src_ip` varchar(50) DEFAULT NULL COMMENT 'source ip',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_configinfotag_datagrouptenanttag` (`data_id`,`group_id`,`tenant_id`,`tag_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='config_info_tag';

/******************************************/
/*   数据库全名 = nacos_config   */
/*   表名称 = config_tags_relation   */
/******************************************/
CREATE TABLE `config_tags_relation` (
  `id` bigint(20) NOT NULL COMMENT 'id',
  `tag_name` varchar(128) NOT NULL COMMENT 'tag_name',
  `tag_type` varchar(64) DEFAULT NULL COMMENT 'tag_type',
  `data_id` varchar(255) NOT NULL COMMENT 'data_id',
  `group_id` varchar(128) NOT NULL COMMENT 'group_id',
  `tenant_id` varchar(128) DEFAULT '' COMMENT 'tenant_id',
  `nid` bigint(20) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`nid`),
  UNIQUE KEY `uk_configtagrelation_configidtag` (`id`,`tag_name`,`tag_type`),
  KEY `idx_tenant_id` (`tenant_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='config_tag_relation';

/******************************************/
/*   数据库全名 = nacos_config   */
/*   表名称 = group_capacity   */
/******************************************/
CREATE TABLE `group_capacity` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `group_id` varchar(128) NOT NULL DEFAULT '' COMMENT 'Group ID,空字符表示整个集群',
  `quota` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '配额,0表示使用默认值',
  `usage` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '使用量',
  `max_size` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '单个配置大小上限,单位为字节,0表示使用默认值',
  `max_aggr_count` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '聚合子配置最大个数,,0表示使用默认值',
  `max_aggr_size` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '单个聚合数据的子配置大小上限,单位为字节,0表示使用默认值',
  `max_history_count` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '最大变更历史数量',
  `gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_group_id` (`group_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='集群、各Group容量信息表';

/******************************************/
/*   数据库全名 = nacos_config   */
/*   表名称 = his_config_info   */
/******************************************/
CREATE TABLE `his_config_info` (
  `id` bigint(20) unsigned NOT NULL,
  `nid` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `data_id` varchar(255) NOT NULL,
  `group_id` varchar(128) NOT NULL,
  `app_name` varchar(128) DEFAULT NULL COMMENT 'app_name',
  `content` longtext NOT NULL,
  `md5` varchar(32) DEFAULT NULL,
  `gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `src_user` text,
  `src_ip` varchar(50) DEFAULT NULL,
  `op_type` char(10) DEFAULT NULL,
  `tenant_id` varchar(128) DEFAULT '' COMMENT '租户字段',
  `encrypted_data_key` text NOT NULL COMMENT '秘钥',
  PRIMARY KEY (`nid`),
  KEY `idx_gmt_create` (`gmt_create`),
  KEY `idx_gmt_modified` (`gmt_modified`),
  KEY `idx_did` (`data_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='多租户改造';


/******************************************/
/*   数据库全名 = nacos_config   */
/*   表名称 = tenant_capacity   */
/******************************************/
CREATE TABLE `tenant_capacity` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `tenant_id` varchar(128) NOT NULL DEFAULT '' COMMENT 'Tenant ID',
  `quota` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '配额,0表示使用默认值',
  `usage` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '使用量',
  `max_size` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '单个配置大小上限,单位为字节,0表示使用默认值',
  `max_aggr_count` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '聚合子配置最大个数',
  `max_aggr_size` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '单个聚合数据的子配置大小上限,单位为字节,0表示使用默认值',
  `max_history_count` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '最大变更历史数量',
  `gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_tenant_id` (`tenant_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='租户容量信息表';


CREATE TABLE `tenant_info` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `kp` varchar(128) NOT NULL COMMENT 'kp',
  `tenant_id` varchar(128) default '' COMMENT 'tenant_id',
  `tenant_name` varchar(128) default '' COMMENT 'tenant_name',
  `tenant_desc` varchar(256) DEFAULT NULL COMMENT 'tenant_desc',
  `create_source` varchar(32) DEFAULT NULL COMMENT 'create_source',
  `gmt_create` bigint(20) NOT NULL COMMENT '创建时间',
  `gmt_modified` bigint(20) NOT NULL COMMENT '修改时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_tenant_info_kptenantid` (`kp`,`tenant_id`),
  KEY `idx_tenant_id` (`tenant_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='tenant_info';

CREATE TABLE `users` (
	`username` varchar(50) NOT NULL PRIMARY KEY,
	`password` varchar(500) NOT NULL,
	`enabled` boolean NOT NULL
);

CREATE TABLE `roles` (
	`username` varchar(50) NOT NULL,
	`role` varchar(50) NOT NULL,
	UNIQUE INDEX `idx_user_role` (`username` ASC, `role` ASC) USING BTREE
);

CREATE TABLE `permissions` (
    `role` varchar(50) NOT NULL,
    `resource` varchar(255) NOT NULL,
    `action` varchar(8) NOT NULL,
    UNIQUE INDEX `uk_role_permission` (`role`,`resource`,`action`) USING BTREE
);

INSERT INTO users (username, password, enabled) VALUES ('nacos', '$2a$10$EuWPZHzz32dJN7jexM34MOeYirDdFAZm2kuWj7VEOJhhZkDrxfvUu', TRUE);

INSERT INTO roles (username, role) VALUES ('nacos', 'ROLE_ADMIN');

2. Modify the configuration file

modify this
insert image description here

(1), backup configuration file

Make a backup copy before modifying, in case the modification is broken and you don’t know how to start over, the backup command is as follows:

cp application.properties application_bk.properties

insert image description here

(2), before modification

# spring
server.servlet.contextPath=${
    
    SERVER_SERVLET_CONTEXTPATH:/nacos}
server.contextPath=/nacos
server.port=${
    
    NACOS_APPLICATION_PORT:8848}
server.tomcat.accesslog.max-days=30
server.tomcat.accesslog.pattern=%h %l %u %t "%r" %s %b %D %{
    
    User-Agent}i %{
    
    Request-Source}i
server.tomcat.accesslog.enabled=${
    
    TOMCAT_ACCESSLOG_ENABLED:false}
# default current work dir
server.tomcat.basedir=file:.
#*************** Config Module Related Configurations ***************#
### Deprecated configuration property, it is recommended to use `spring.sql.init.platform` replaced.
#spring.datasource.platform=${
    
    SPRING_DATASOURCE_PLATFORM:}
spring.sql.init.platform=${
    
    SPRING_DATASOURCE_PLATFORM:}
nacos.cmdb.dumpTaskInterval=3600
nacos.cmdb.eventTaskInterval=10
nacos.cmdb.labelTaskInterval=300
nacos.cmdb.loadDataAtStart=false
db.num=${
    
    MYSQL_DATABASE_NUM:1}
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}
db.user.0=${
    
    MYSQL_SERVICE_USER}
db.password.0=${
    
    MYSQL_SERVICE_PASSWORD}
### The auth system to use, currently only 'nacos' and 'ldap' is supported:
nacos.core.auth.system.type=${
    
    NACOS_AUTH_SYSTEM_TYPE:nacos}
### worked when nacos.core.auth.system.type=nacos
### The token expiration in seconds:
nacos.core.auth.plugin.nacos.token.expire.seconds=${
    
    NACOS_AUTH_TOKEN_EXPIRE_SECONDS:18000}
### The default token:
nacos.core.auth.plugin.nacos.token.secret.key=${
    
    NACOS_AUTH_TOKEN}
### 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=${
    
    NACOS_AUTH_CACHE_ENABLE:false}
nacos.core.auth.enable.userAgentAuthWhite=${
    
    NACOS_AUTH_USER_AGENT_AUTH_WHITE_ENABLE:false}
nacos.core.auth.server.identity.key=${
    
    NACOS_AUTH_IDENTITY_KEY}
nacos.core.auth.server.identity.value=${
    
    NACOS_AUTH_IDENTITY_VALUE}
## spring security config
### turn off security
nacos.security.ignore.urls=${
    
    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

(3) After modification (there are many solutions to stepping on the pit, it is recommended not to skip it when installing nacos for the first time)

# spring
server.servlet.contextPath=/nacos
server.contextPath=/nacos
server.port=8848
# server.tomcat.accesslog.max-days=30
# server.tomcat.accesslog.pattern=%h %l %u %t "%r" %s %b %D %{
    
    User-Agent}i %{
    
    Request-Source}i
# server.tomcat.accesslog.enabled=false
# default current work dir
# server.tomcat.basedir=file:.
#*************** Config Module Related Configurations ***************#
### Deprecated configuration property, it is recommended to use `spring.sql.init.platform` replaced.
spring.datasource.platform=mysql
spring.sql.init.platform=mysql
nacos.cmdb.dumpTaskInterval=3600
nacos.cmdb.eventTaskInterval=10
nacos.cmdb.labelTaskInterval=300
nacos.cmdb.loadDataAtStart=false
db.num=1
#  这里必须为公网或服务器内网地址,我这里是服务器的内网地址,容器内部没有mysql,绝对不能使用 127.0.0.1和localhost

#  如果nacos启动失败,Nacos Server did not start because dumpservice bean construction failure : No DataSource set
#  加上 &serverTimezone=UTC ,再不行就加上 &allowPublicKeyRetrieval=true

#  将connectTimeout 和 socketTimeout 分别加个0,避免出现超时异常
db.url.0=jdbc:mysql://公网或服务器内网地址:3306/cj-config?characterEncoding=utf8&connectTimeout=10000&socketTimeout=30000&autoReconnect=true&useUnicode=true&useSSL=false
db.user.0=root
db.password.0=123456

### The auth system to use, currently only 'nacos' and 'ldap' is supported:
# 鉴权类型,默认为nacos
nacos.core.auth.system.type=nacos

# 是否开启鉴权功能,默认为false
nacos.core.auth.enabled=true

# Base64加密前密码  TcmxJw05k$-_zcx.)8EtFC^D^F1W!IPr
# Base64加密后密码  VGNteEp3MDVrJC1femN4Lik4RXRGQ15EXkYxVyFJUHI=
# 加密网站:https://www.qqxiuzi.cn/bianma/base64.htm
# 自定义密钥,在自定义密钥时,推荐将配置项设置为Base64编码的字符串,且原始密钥长度不得低于32字符。同nacos.core.auth.plugin.nacos.token.secret.key
nacos.core.auth.default.token.secret.key=VGNteEp3MDVrJC1femN4Lik4RXRGQ15EXkYxVyFJUHI=

### worked when nacos.core.auth.system.type=nacos
### The token expiration in seconds:
# 用户登陆临时accessToken的过期时间,默认18000
nacos.core.auth.plugin.nacos.token.expire.seconds=18000
### The default token:

# 默认鉴权插件用于生成用户登陆临时accessToken所使用的密钥,在2.2.0.1后无默认值,必须执行此变更,否则无法启动;其他版本为建议设置。
nacos.core.auth.plugin.nacos.token.secret.key=VGNteEp3MDVrJC1femN4Lik4RXRGQ15EXkYxVyFJUHI=
### 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=${
    
    NACOS_AUTH_CACHE_ENABLE:false}

# 关闭使用user-agent判断服务端请求并放行鉴权的功能
nacos.core.auth.enable.userAgentAuthWhite=false

# 用于替换useragent白名单的身份识别key,不可为空,2.2.1后无默认值
nacos.core.auth.server.identity.key=nacosKey
# 用于替换useragent白名单的身份识别value,不可为空,2.2.1后无默认值
nacos.core.auth.server.identity.value=nacosValue

## 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

6. Start nacos

Use the following command to start this time, pay attention to change the IP address to the public network address of your server

docker run -d --name nacos \
--ip 0.0.0.0 \
-p 8848:8848 \
-p 9848:9848 \
-p 9849:9849 \
--env MODE=standalone \
--env NACOS_AUTH_ENABLE=true \
-v /www/wwwroot/changjing/docker/nacos/conf/:/home/nacos/conf \
-v /www/wwwroot/changjing/docker/nacos/logs:/home/nacos/logs \
-v /www/wwwroot/changjing/docker/nacos/data:/home/nacos/data \
nacos/nacos-server:v2.2.1

insert image description here

explain:

docker run -d --name nacos \                                            -d 表示运行在后台,--name 指定名称为nacos
--ip 8.134.131.48 \                                                     自定义分配 IP 地址,我写的是服务器的 IP 地址,可忽略
-p 8848:8848 \                                                          前者为暴露给外部访问的端口,后者为nacos容器端口
-p 9848:9848 \                                                          9848是nacos2.0.0版本以上必须要加上端口映射
-p 9849:9849 \                                                          9849是nacos2.0.0版本以上必须要加上端口映射
--env MODE=standalone \                                                 nacos以单机版启动,默认为cluster(集群)
--env NACOS_AUTH_ENABLE=true \                                          如果使用官方镜像,请在启动docker容器时,添加如下环境变量
-v /www/wwwroot/changjing/docker/nacos/conf/:/home/nacos/conf \         nacos 配置文件目录,“:”前为服务器目录,“:”后为nacos容器中的目录
-v /www/wwwroot/changjing/docker/nacos/logs:/home/nacos/logs \          nacos 日志文件目录,“:”前为服务器目录,“:”后为nacos容器中的目录
-v /www/wwwroot/changjing/docker/nacos/data:/home/nacos/data \          nacos 数据文件目录,“:”前为服务器目录,“:”后为nacos容器中的目录
nacos/nacos-server:v2.2.1                                               指定 docker nacos 版本,这里是2.2.1版本

Versions above nacos2.0.0 need to enable authentication, see here for details:

https://nacos.io/zh-cn/docs/v2/guide/user/auth.html

If there is no accident at this time, there should be some accident, and an error will be reported when starting this time.

insert image description here

Because it was started once in order to copy the relevant files of the container, although the startup failed, a container named nacos has already been created.

Delete it first, the command is as follows:

docker rm -f nacos

insert image description here

start the container again

insert image description here
You can see that the container is successful.

Go to the browser and use the IP address or domain name to access:
insert image description here

Seven, stepping on the pit record

1. Tomcat failed to start

insert image description here
I don’t know if there are any friends like me. When I saw the first error, Tomcat failed to start, I thought it was necessary to install the Tomcat image and start it. In fact, it is not necessary. The real error message is later.

2、Caused by: java.lang.IllegalArgumentException: the length of secret key must great than or equal 32 bytes; And the secret key must be encoded by base64

This mistake should be encountered by many friends

Caused by: java.lang.IllegalArgumentException: the length of secret key must great than or equal 32 bytes; And the secret key  must be encoded by base64.Please see https://nacos.io/zh-cn/docs/v2/guide/user/auth.html
	at com.alibaba.nacos.plugin.auth.impl.token.impl.JwtTokenManager.processProperties(JwtTokenManager.java:73)
	at com.alibaba.nacos.plugin.auth.impl.token.impl.JwtTokenManager.<init>(JwtTokenManager.java:61)
	at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
	at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
	at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
	at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
	at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:211)
	... 112 common frames omitted
Caused by: java.lang.IllegalArgumentException: The specified key byte array is 0 bits which is not secure enough for any JWT HMAC-SHA algorithm.  The JWT JWA Specification (RFC 7518, Section 3.2) states that keys used with HMAC-SHA algorithms MUST have a size >= 256 bits (the key size must be greater than or equal to the hash output size).  See https://tools.ietf.org/html/rfc7518#section-3.2 for more information.
	at com.alibaba.nacos.plugin.auth.impl.jwt.NacosJwtParser.<init>(NacosJwtParser.java:56)
	at com.alibaba.nacos.plugin.auth.impl.token.impl.JwtTokenManager.processProperties(JwtTokenManager.java:71)
	... 118 common frames omitted
2023-08-08 14:41:45,798 WARN [ThreadPoolManager] Start destroying ThreadPool

2023-08-08 14:41:45,798 WARN [ThreadPoolManager] Destruction of the end

insert image description here
Said that there is a lack of a secret key that should be no less than 32 in length, and released all the official documents

https://nacos.io/zh-cn/docs/v2/guide/user/auth.html

This is it

insert image description here

nacos.core.auth.plugin.nacos.token.secret.key The default authentication plugin is used to generate the key used by the user to log in to the temporary accessToken. There is no default value after 2.2.0.1. This change must be performed, otherwise it cannot be started; Other versions are recommended settings

Mine is nacos2.2.1 version, that is, there is no default value, and no modification was made at that time, and an error will be reported when it starts. Assign a value to nacos.core.auth.plugin.nacos.token.secret.key (32-bit and above Base64 encoded string), start again

insert image description here
If you have carefully read the nacos documentation and made corresponding modifications, it should be a successful startup. If not, continue reading.

3、Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘authConfigs’: Invocation of init method failed; nested exception is ErrCode:50002, ErrMsg:Empty identity, Please set nacos.core.auth.server.identity.key and nacos.core.auth.server.identity.value

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'authConfigs': Invocation of init method failed; nested exception is ErrCode:50002, ErrMsg:Empty identity, Please set `nacos.core.auth.server.identity.key` and `nacos.core.auth.server.identity.value`, detail: https://nacos.io/zh-cn/docs/v2/guide/user/auth.html
	at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:160)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:440)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1796)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:620)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542)
	at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)
	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
	at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1391)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1311)
	at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:887)
	at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:791)
	... 75 common frames omitted
Caused by: com.alibaba.nacos.api.exception.NacosException: Empty identity, Please set `nacos.core.auth.server.identity.key` and `nacos.core.auth.server.identity.value`, detail: https://nacos.io/zh-cn/docs/v2/guide/user/auth.html
	at com.alibaba.nacos.auth.config.AuthConfigs.validate(AuthConfigs.java:100)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:389)
	at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:333)
	at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:157)
	... 88 common frames omitted
2023-08-08 15:03:01,939 WARN [ThreadPoolManager] Start destroying ThreadPool

insert image description here

Official documentation:

https://nacos.io/zh-cn/docs/v2/guide/user/auth.html

This is the key and value without custom identification
insert image description here
plus the corresponding configuration, restart nacos again

insert image description here
If you have carefully read the nacos documentation and made corresponding modifications, then there should be no problem with authentication. Also note that nacos.core.auth.default.token.secret.key, the documentation says and

同nacos.core.auth.plugin.nacos.token.secret.key

But I tried it, commenting out nacos.core.auth.default.token.secret.key can also start successfully, but just add it for insurance.

insert image description here

At this point, if you don't succeed, go on and look down.

4、Caused by: com.alibaba.nacos.api.exception.NacosException: Nacos Server did not start because dumpservice bean construction failure : No DataSource set

Caused by: com.alibaba.nacos.api.exception.NacosException: Nacos Server did not start because dumpservice bean construction failure :
No DataSource set
	at com.alibaba.nacos.config.server.service.dump.DumpService.dumpOperate(DumpService.java:260)
	at com.alibaba.nacos.config.server.service.dump.ExternalDumpService.init(ExternalDumpService.java:61)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:389)
	at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:333)
	at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:157)
	... 54 common frames omitted
Caused by: java.lang.IllegalStateException: No DataSource set
	at org.springframework.util.Assert.state(Assert.java:76)
	at org.springframework.jdbc.support.JdbcAccessor.obtainDataSource(JdbcAccessor.java:86)
	at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:376)
	at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:465)
	at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:475)
	at org.springframework.jdbc.core.JdbcTemplate.queryForObject(JdbcTemplate.java:508)
	at org.springframework.jdbc.core.JdbcTemplate.queryForObject(JdbcTemplate.java:515)
	at com.alibaba.nacos.config.server.service.repository.extrnal.ExternalConfigInfoPersistServiceImpl.findConfigMaxId(ExternalConfigInfoPersistServiceImpl.java:632)
	at com.alibaba.nacos.config.server.service.dump.processor.DumpAllProcessor.process(DumpAllProcessor.java:51)
	at com.alibaba.nacos.config.server.service.dump.DumpService.dumpConfigInfo(DumpService.java:317)
	at com.alibaba.nacos.config.server.service.dump.DumpService.dumpOperate(DumpService.java:230)
	... 62 common frames omitted
2023-08-08 15:32:34,341 WARN [ThreadPoolManager] Start destroying ThreadPool

insert image description here
It says that the data source is not set, and after careful inspection, it is found that the information in the database connection is correct, but the connection cannot be made alive.

We have to understand that nacos is in the docker container, not in the host machine. Change the IP address of mysql to the IP address of the server or the intranet address
insert image description here

restart again

insert image description here
Finally succeeded! ! !

Replenish:

There are also posts on the Internet saying that the two values ​​of connectTimeout and socketTimeout are too small, and this error will also be reported when the database connection takes a long time, but I have not encountered it. Here, 0 is added to these two values ​​respectively.

Guess you like

Origin blog.csdn.net/studio_1/article/details/132160081