alibaba / nacos

an easy-to-use dynamic service discovery, configuration and service management platform for building cloud native applications.
https://nacos.io
Apache License 2.0
30.39k stars 12.87k forks source link

Nacos(2.0.3) on Docker, No DataSource set #6886

Closed wangjiandev closed 2 years ago

wangjiandev commented 3 years ago

Issue Description

Type: bug report or feature request

使用docker启动发现无法启动,数据库可以在外部连接,数据已经初始化。

/home/nacos/logs/nacos.log

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:236)
    at com.alibaba.nacos.config.server.service.dump.ExternalDumpService.init(ExternalDumpService.java:52)
    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:363)
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:307)
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:136)
    ... 53 common frames omitted
Caused by: java.lang.IllegalStateException: No DataSource set
    at org.springframework.util.Assert.state(Assert.java:73)
    at org.springframework.jdbc.support.JdbcAccessor.obtainDataSource(JdbcAccessor.java:77)
    at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:371)
    at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:452)
    at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:462)
    at org.springframework.jdbc.core.JdbcTemplate.queryForObject(JdbcTemplate.java:473)
    at org.springframework.jdbc.core.JdbcTemplate.queryForObject(JdbcTemplate.java:480)
    at com.alibaba.nacos.config.server.service.repository.extrnal.ExternalStoragePersistServiceImpl.findConfigMaxId(ExternalStoragePersistServiceImpl.java:658)
    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:293)
    at com.alibaba.nacos.config.server.service.dump.DumpService.dumpOperate(DumpService.java:205)

standalone-mysql-8.yaml

version: "2"
services:
  nacos:
    image: nacos/nacos-server:${NACOS_VERSION}
    container_name: nacos-standalone-mysql
    env_file:
      - ../env/nacos-standlone-mysql.env
    volumes:
      - ./standalone-logs/:/home/nacos/logs
      - ./plugins/:/home/nacos/plugins
      - ./init.d/custom.properties:/home/nacos/init.d/custom.properties
    ports:
      - "8848:8848"
      - "9848:9848"
      - "9555:9555"
    depends_on:
      - mysql
    restart: always
  mysql:
    container_name: mysql
    image: nacos/nacos-mysql:8.0.16
    env_file:
      - ../env/mysql.env
    volumes:
      - ./mysql:/var/lib/mysql
    ports:
      - "3306:3306"

尝试加载驱动文件并挂载到/home/nacos/plugins/mysql,没有解决

尝试修改配置文件

env/nacos-standlone-mysql.env

PREFER_HOST_MODE=hostname
MODE=standalone
SPRING_DATASOURCE_PLATFORM=mysql
MYSQL_SERVICE_HOST=mysql
MYSQL_SERVICE_DB_NAME=nacos_devtest
MYSQL_SERVICE_PORT=3306
MYSQL_SERVICE_USER=nacos
MYSQL_SERVICE_PASSWORD=nacos
MYSQL_SERVICE_DB_PARAM=characterEncoding=utf8&connectTimeout=10000&socketTimeout=30000&autoReconnect=true&useSSL=false&serverTimezone=UTC

加入serverTimezone=UTC配置,并且修改超时时间,同样没有修复

brotherlu-xcq commented 3 years ago

你检查一下你db和表是初始化好了。

realJackSun commented 3 years ago

在数据库里面 source nacos-mysql.sql一下

blank-1 commented 3 years ago

同样的问题,肯定是bug

ageovb commented 3 years ago

使用 Docker 安装的,进入容器,在 /home/nacos/conf/application.properties 将数据源切换为 MySQL 即可,因为 Docker 里面默认没有配置数据源。

iamzxj commented 3 years ago

为什么在docker-compose指定了参数也不行, image

iamzxj commented 3 years ago

别的参数都生效了

muyu66 commented 3 years ago

已经找了一个小时了,还没找到nacos-mysql.sql初始化数据库的sql在哪。。

tinytik commented 3 years ago

数据库访问异常时会抛出该异常

异常分析

DumpService

    @PostConstruct
    @Override
    protected void init() throws Throwable {
        dumpOperate(processor, dumpAllProcessor, dumpAllBetaProcessor, dumpAllTagProcessor);
    }

DumpService的dumpOperate

 protected void dumpOperate(DumpProcessor processor, DumpAllProcessor dumpAllProcessor,  DumpAllBetaProcessor dumpAllBetaProcessor, DumpAllTagProcessor dumpAllTagProcessor) throws NacosException {
    ……
      dumpConfigInfo(dumpAllProcessor);
    ……
  }

DumpService的dumpConfigInfo

    private void dumpConfigInfo(DumpAllProcessor dumpAllProcessor) throws IOException {
               ……
             dumpAllProcessor.process(new DumpAllTask());
              ……
   }

DumpAllProcessor的process方法

public boolean process(NacosTask task) {
        long currentMaxId = persistService.findConfigMaxId();//查询最大ID
}

ExternalStoragePersistServiceImpl的findConfigMaxId

public long findConfigMaxId() {
        String sql = "SELECT max(id) FROM config_info";
        try {
            //此处支持数据库查询时会抛出No DataSource set 异常,原因是jt(JdbcTemplate)的dataSource是空导致的
            return jt.queryForObject(sql, Long.class);
        } catch (NullPointerException e) {
            return 0;
        }
    }

ExternalStoragePersistServiceImpl的init方法

    protected JdbcTemplate jt;
    @PostConstruct
    public void init() {
        dataSourceService = DynamicDataSource.getInstance().getDataSource();
        jt = getJdbcTemplate();
        tjt = getTransactionTemplate();
    }

ExternalStoragePersistServiceImpl的getJdbcTemplate方法

    public JdbcTemplate getJdbcTemplate() {
        return this.dataSourceService.getJdbcTemplate();
    }

ExternalDataSourceServiceImpl的getJdbcTemplate

    @Override
    public JdbcTemplate getJdbcTemplate() {
       //既然是this那就看下在当前类jt在那初始化的
        return this.jt;
    }

ExternalDataSourceServiceImpl的init

private JdbcTemplate jt;

public void init() {
      ……
        jt = new JdbcTemplate();
        // Set the maximum number of records to prevent memory expansion
        jt.setMaxRows(50000);
        jt.setQueryTimeout(queryTimeout);
        //数据源怎么没set进去啊?继续跟吧!
        if (PropertyUtil.isUseExternalDB()) {
            try {
                reload();//没猜错应该是在这个方法
            } catch (IOException e) {
                FATAL_LOG.error("[ExternalDataSourceService] dats source reload error", e);
                throw new RuntimeException(DB_LOAD_ERROR_MSG);
            }

            if (this.dataSourceList.size() > DB_MASTER_SELECT_THRESHOLD) {
                ConfigExecutor.scheduleConfigTask(new SelectMasterTask(), 10, 10, TimeUnit.SECONDS);
            }
            ConfigExecutor.scheduleConfigTask(new CheckDbHealthTask(), 10, 10, TimeUnit.SECONDS);
        }
       ……
}

ExternalDataSourceServiceImpl的reload方法

    @Override
    public synchronized void reload() throws IOException {
        try {
            dataSourceList = new ExternalDataSourceProperties()
                    .build(EnvUtil.getEnvironment(), (dataSource) -> {
                        JdbcTemplate jdbcTemplate = new JdbcTemplate();
                        jdbcTemplate.setQueryTimeout(queryTimeout);
                        jdbcTemplate.setDataSource(dataSource);
                        testJtList.add(jdbcTemplate);
                        isHealthList.add(Boolean.TRUE);
                    });
           //选主
            new SelectMasterTask().run();
            new CheckDbHealthTask().run();
        } catch (RuntimeException e) {
            FATAL_LOG.error(DB_LOAD_ERROR_MSG, e);
            throw new IOException(e);
        }
    }

class SelectMasterTask implements Runnable {
        @Override
        public void run() {
            ……
            for (HikariDataSource ds : dataSourceList) {
                index++;
                testMasterJT.setDataSource(ds);
                testMasterJT.setQueryTimeout(queryTimeout);
                try {
                    testMasterJT.update("DELETE FROM config_info WHERE data_id='com.alibaba.nacos.testMasterDB'")
                    if (jt.getDataSource() != ds) {
                        FATAL_LOG.warn("[master-db] {}", ds.getJdbcUrl());
                    }
                   //我靠,终于找到了……那为啥没set进去?
                    jt.setDataSource(ds);
                   ……
                } catch (DataAccessException e) { // read only
                    FATAL_LOG.warn("[master-db] master db access error", e);
                }
            }
            ……
        }
    }

到此你应该明白为啥了吧 testMasterJT.update("DELETE FROM config_info WHERE data_id='com.alibaba.nacos.testMasterDB'"); 执行时一旦报错KPI大神们只给你了一个 FATAL_LOG.warn("[master-db] master db access error", e); warn级别的日志……一万个XXX

TrueVoid commented 3 years ago

启动nacos的时候mysql数据库还没有ready。你再重启下就可以了。 docker-compose restart

------------------ 原始邮件 ------------------ 发件人: "alibaba/nacos" @.>; 发送时间: 2021年9月15日(星期三) 下午5:34 @.>; @.***>; 主题: [alibaba/nacos] Nacos(2.0.3) on Docker, No DataSource set (#6886)

Issue Description

Type: bug report or feature request

使用docker启动发现无法启动,数据库可以在外部连接,数据已经初始化。

/home/nacos/logs/nacos.log 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:236) at com.alibaba.nacos.config.server.service.dump.ExternalDumpService.init(ExternalDumpService.java:52) 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:363) at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:307) at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:136) ... 53 common frames omitted Caused by: java.lang.IllegalStateException: No DataSource set at org.springframework.util.Assert.state(Assert.java:73) at org.springframework.jdbc.support.JdbcAccessor.obtainDataSource(JdbcAccessor.java:77) at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:371) at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:452) at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:462) at org.springframework.jdbc.core.JdbcTemplate.queryForObject(JdbcTemplate.java:473) at org.springframework.jdbc.core.JdbcTemplate.queryForObject(JdbcTemplate.java:480) at com.alibaba.nacos.config.server.service.repository.extrnal.ExternalStoragePersistServiceImpl.findConfigMaxId(ExternalStoragePersistServiceImpl.java:658) 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:293) at com.alibaba.nacos.config.server.service.dump.DumpService.dumpOperate(DumpService.java:205)
standalone-mysql-8.yaml version: "2" services: nacos: image: nacos/nacos-server:${NACOS_VERSION} container_name: nacos-standalone-mysql env_file: - ../env/nacos-standlone-mysql.env volumes: - ./standalone-logs/:/home/nacos/logs - ./plugins/:/home/nacos/plugins - ./init.d/custom.properties:/home/nacos/init.d/custom.properties ports: - "8848:8848" - "9848:9848" - "9555:9555" depends_on: - mysql restart: always mysql: container_name: mysql image: nacos/nacos-mysql:8.0.16 env_file: - ../env/mysql.env volumes: - ./mysql:/var/lib/mysql ports: - "3306:3306"
尝试加载驱动文件并挂载到/home/nacos/plugins/mysql,没有解决

尝试修改配置文件

env/nacos-standlone-mysql.env PREFER_HOST_MODE=hostname MODE=standalone SPRING_DATASOURCE_PLATFORM=mysql MYSQL_SERVICE_HOST=mysql MYSQL_SERVICE_DB_NAME=nacos_devtest MYSQL_SERVICE_PORT=3306 MYSQL_SERVICE_USER=nacos MYSQL_SERVICE_PASSWORD=nacos MYSQL_SERVICE_DB_PARAM=characterEncoding=utf8&connectTimeout=10000&socketTimeout=30000&autoReconnect=true&useSSL=false&serverTimezone=UTC
加入serverTimezone=UTC配置,并且修改超时时间,同样没有修复

— You are receiving this because you are subscribed to this thread. Reply to this email directly, view it on GitHub, or unsubscribe. Triage notifications on the go with GitHub Mobile for iOS or Android.

fly2light commented 2 years ago

你可以在容器内试着curl请求下数据库的host:port,看看数据库在容器内是否能够访问

albertPu commented 2 years ago

没人解决?

HandsomeBoy01 commented 2 years ago

真的服了,我也遇见了!!!诶

yhm-amber commented 2 years ago

same issue

我是用 helm 安装的:

: get chart
git pull -- https://github.com/nacos-group/nacos-k8s nacos-group/nacos-k8s && cd nacos-group/nacos-k8s

: install
helm install -n nacos-yourns --create-namespace --set $(

    echo '

        nacos.image.repository=nacos/nacos-server
        nacos.env.serverPort=8848

        service.type=NodePort
        service.port=8848
        service.nodePort=30848

        global.mode=cluster
        nacos.replicaCount=3

        ingress.enabled=false

        nacos.plugin.enable=true
        nacos.plugin.image.repository=nacos/nacos-peer-finder-plugin

        nacos.storage.type=mysql
        nacos.storage.db.host=mysql-leader.meta-db.svc.cluster.local
        nacos.storage.db.port=3306
        nacos.storage.db.name=nacos
        nacos.storage.db.username=nacos
        nacos.storage.db.password=P@88w0rd--nacos

        ' | xargs -i -- printf %s, {} | xargs -d, | tr ' ' , &&
    : ) -- nacos-cluster ./helm

out:

NAME: nacos-cluster
LAST DEPLOYED: Wed Jun 22 14:33:57 2022
NAMESPACE: nacos-yourns
STATUS: deployed
REVISION: 1
TEST SUITE: None
NOTES:
1. Get the application URL by running these commands:
  export NODE_PORT=$(kubectl get --namespace nacos-yourns -o jsonpath="{.spec.ports[0].nodePort}" services  nacos-cs)
  export NODE_IP=$(kubectl get nodes --namespace nacos-yourns -o jsonpath="{.items[0].status.addresses[0].address}")
  echo http://$NODE_IP:$NODE_PORT/nacos
2. MODE:
   standalone: you need to modify replicaCount in the values.yaml, .Values.replicaCount=1
   cluster: kubectl scale sts nacos-yourns-nacos --replicas=3

但容器不能就绪:

image

从这里看环境变量配置也没问题。

这个数据库地址也没问题,能用 mysql -h -u -p'' 的形式成功连接,也有相应数据库。


对应的 nacos 库是手动创建,并给过权限,里面什么也没做,全新的。

image

难道需要用户手动创建需要的表吗?但这是不是应当是由 nacos 的开发来,在文档或者 init-container 规定才对的?。。。

yhm-amber commented 2 years ago

你可以在容器内试着curl请求下数据库的host:port,看看数据库在容器内是否能够访问

@fly2light 尝试这个操作,打印了这个:

5.7.34-37-logx]m90sCOD��-��B-n`E:],mysql_native_password!��#08S01Got packets out of order

看起来并不是连不上

yhm-amber commented 2 years ago

我解决了

我在我的 nacos 数据库应用了 distribution/conf/nacos-mysql.sql 里面 的SQL ,就没什么问题了。

(我这个是切换 tag 到版本 2.0.3 了,你们谁需要的话注意切到对应的 tag 版本上。)

nacos-mysql-2.0.3.sql ~~~ mysql /* * 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. */ /******************************************/ /* 数据库全名 = nacos_config */ /* 表名称 = config_info */ /******************************************/ 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(255) 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, 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(255) 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 '租户字段', 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(64) 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 '租户字段', 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'); ~~~

但,我认为我为 Nacos 创建的数据库,应当就是空着的,然后 Nacos 看我指定的数据库是空的,就会自行在其中做必要的 source nacos-mysql.sql

我找了一下, nacos/nacos-server:2.0.3 的镜像内,并没有 nacos-mysql.sql 这个文件,但是在 Release 的压缩包和源码中都可以找到这个文件。

这意味着, Nacos 并没有被赋予在自己被指定的 database 中自动初始化 MySQL 表的能力。

但我认为这是需要有的能力。所以,这依然是一个问题,至少在 2.0.3 版本存在这个问题,我只是找到了手动修复的途径罢了。

希望在未来版本的 Helm 或 Operator 部署中可以为 Nacos 增加自动初始化外部数据库的能力:只要那个库是空的,就要执行初始化(这应该会需要用到至少一个 Init Container 吧);如果被指定的目标库不为空但是缺少表,也最好明确报错出还缺少什么表、或什么表结构不正确,而不是像现在这样,在显眼位置的有用的信息只有一个 No DataSource set 而已。

liangchen-datanerd commented 2 years ago

same issue!

liangchen-datanerd commented 2 years ago

这个解决了问题,我在config_info里边加了一条data_id为testMasterDB就能启动了! 这么多人提的问题官方都不解决下!

qumj123 commented 1 year ago

docker run -d \ -e MODE=standalone \ -e SPRING_DATASOURCE_PLATFORM=mysql \ -e MYSQL_SERVICE_HOST=172.18.0.2 \ -e MYSQL_SERVICE_PORT=3306 \ -e MYSQL_SERVICE_USER=root \ -e MYSQL_SERVICE_PASSWORD=123456 \ -e MYSQL_SERVICE_DB_NAME=nacos \ -e MYSQL_SERVICE_DB_PARAM='characterEncoding=utf8&connectTimeout=10000&socketTimeout=30000&autoReconnect=true&useSSL=false&serverTimezone=UTC' \ -v /data/docker/nacos/logs:/home/nacos/logs \ -v /data/docker/nacos/conf:/home/nacos/conf \ --network qu-net \ -p 8848:8848 -p 9848:9848 -p 9849:9849 \ --name nacos \ nacos/nacos-server

qumj123 commented 1 year ago

2022-12-14 17:56:42,234 WARN [WatchFileCenter] start close

2022-12-14 17:56:42,234 WARN [WatchFileCenter] start to shutdown this watcher which is watch : /home/nacos/data/tps

2022-12-14 17:56:42,234 WARN [WatchFileCenter] start to shutdown this watcher which is watch : /home/nacos/conf

2022-12-14 17:56:42,234 WARN [WatchFileCenter] start to shutdown this watcher which is watch : /home/nacos/data/loader

2022-12-14 17:56:42,234 WARN [WatchFileCenter] already closed

2022-12-14 17:56:42,234 WARN [NotifyCenter] Start destroying Publisher

2022-12-14 17:56:42,235 WARN [NotifyCenter] Destruction of the end

2022-12-14 17:56:42,235 ERROR Nacos failed to start, please see /home/nacos/logs/nacos.log for more details.

2022-12-14 17:56:42,250 INFO

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.

2022-12-14 17:56:42,252 ERROR Application run failed

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'memoryMonitor' defined in URL [jar:file:/home/nacos/target/nacos-server.jar!/BOOT-INF/lib/nacos-config-2.0.3.jar!/com/alibaba/nacos/config/server/monitor/MemoryMonitor.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'asyncNotifyService': Unsatisfied dependency expressed through field 'dumpService'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'externalDumpService': Invocation of init method failed; nested exception is ErrCode:500, ErrMsg:Nacos Server did not start because dumpservice bean construction failure : No DataSource set at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:769) at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:218) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1338) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1185) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:554) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:514) at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:321) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:319) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:866) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550) at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141) at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:744) at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:391) at org.springframework.boot.SpringApplication.run(SpringApplication.java:312) at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215) at org.springframework.boot.SpringApplication.run(SpringApplication.java:1204) at com.alibaba.nacos.Nacos.main(Nacos.java:35) 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.boot.loader.MainMethodRunner.run(MainMethodRunner.java:49) at org.springframework.boot.loader.Launcher.launch(Launcher.java:108) at org.springframework.boot.loader.Launcher.launch(Launcher.java:58) at org.springframework.boot.loader.PropertiesLauncher.main(PropertiesLauncher.java:467) Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'asyncNotifyService': Unsatisfied dependency expressed through field 'dumpService'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'externalDumpService': Invocation of init method failed; nested exception is ErrCode:500, ErrMsg:Nacos Server did not start because dumpservice bean construction failure : No DataSource set at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:598) at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:376) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1402) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:591) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:514) at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:321) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:319) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:277) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1276) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1196) at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:857) at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:760) ... 27 common frames omitted Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'externalDumpService': Invocation of init method failed; nested exception is ErrCode:500, ErrMsg:Nacos Server did not start because dumpservice bean construction failure : No DataSource set at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:139) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:413) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1761) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:592) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:514) at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:321) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:319) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:277) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1276) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1196) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:595) ... 41 common frames omitted 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:236) at com.alibaba.nacos.config.server.service.dump.ExternalDumpService.init(ExternalDumpService.java:52) 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:363) at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:307) at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:136) ... 53 common frames omitted Caused by: java.lang.IllegalStateException: No DataSource set at org.springframework.util.Assert.state(Assert.java:73) at org.springframework.jdbc.support.JdbcAccessor.obtainDataSource(JdbcAccessor.java:77) at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:371) at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:452) at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:462) at org.springframework.jdbc.core.JdbcTemplate.queryForObject(JdbcTemplate.java:473) at org.springframework.jdbc.core.JdbcTemplate.queryForObject(JdbcTemplate.java:480) at com.alibaba.nacos.config.server.service.repository.extrnal.ExternalStoragePersistServiceImpl.findConfigMaxId(ExternalStoragePersistServiceImpl.java:658) 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:293) at com.alibaba.nacos.config.server.service.dump.DumpService.dumpOperate(DumpService.java:205) ... 61 common frames omitted

qumj123 commented 1 year ago

所有我都尝试过了,依然没有解决。

rayshen3 commented 1 year ago

一样的问题,快解决吐了,所有办法都试过了,还是报java.lang.IllegalStateException: No DataSource set,恶心死了

dinobot71 commented 1 year ago

Late to the party, but I found for running nacos and MySQL in Docker compose, if you are using a modern MySQL (>= 8.x), you have to enable public key exchange on the JDBC connection...even if you are disabling SSL (they are separate things). The older MySQL used an in the clear method to send the password; the newer versions don't do that...so if you haven't enabled public key exchange on the JDBC connection...nacos will always fail; the JDBC driver fails, then the DataSource fails, and then you just get an exception about there not being a data source...even though there is.

My docker compose (which works without any problems - but note that I'm pre-filling the database with a copy of a database I already know has configurations and stuff in it, i.e. the schema is already created):

version: '3'

services:

  # create an instance of ubuntu just to use as our debugging node to
  # test networking between containers.

  ubuntu:
    image: ubuntu:20.04
    container_name: ubuntu
    command: ["sleep","infinity"]

  mysql:
    image: mysql:8.0.32
    container_name: mysql
    hostname: mysql
    ports:
      - "3306:3306"
    environment:
      - MYSQL_ROOT_PASSWORD=nacos
      - MYSQL_DATABASE=nacos
      - MYSQL_USER=nacos
      - MYSQL_PASSWORD=nacos
    healthcheck:
      test: [ "CMD", "mysqladmin" ,"ping", "-h", "localhost" ]
      interval: 5s
      timeout: 10s
      retries: 10

    volumes:
      - ../nacos.sql:/docker-entrypoint-initdb.d/nacos.sql

  nacos:
    image: nacos/nacos-server:latest
    container_name: nacos-server
    hostname: nacos
    environment:
      - PREFER_HOST_MODE=hostname
      - MODE=standalone
      - SPRING_DATASOURCE_PLATFORM=mysql
      - MYSQL_SERVICE_HOST=mysql
      - MYSQL_SERVICE_DB_NAME=nacos
      - MYSQL_SERVICE_PORT=3306
      - MYSQL_SERVICE_USER=nacos
      - MYSQL_SERVICE_PASSWORD=nacos
      - MYSQL_SERVICE_DB_PARAM=characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useSSL=false&allowPublicKeyRetrieval=true
    volumes:
      - ./nacos-logs/:/home/nacos/logs
      - ./nacos-server/conf/application.properties/:/home/nacos/conf/application.properties
      - ./nacos-server/bin/docker-startup.sh/:/home/nacos/bin/docker-startup.sh
    ports:
      - "8848:8848"
      - "9848:9848"
      - "9555:9555"
    depends_on:
      mysql:
        condition: service_healthy
    #restart: always

You can read about the public key exchange issue over here:

https://stackoverflow.com/questions/50379839/connection-java-mysql-public-key-retrieval-is-not-allowed https://docs.spring.io/spring-boot/docs/2.1.9.RELEASE/reference/html/boot-features-external-config.html https://stackoverflow.com/questions/60757590/logging-hikaricp-spring-boot

In the application.properties file I added:

logging.level.com.zaxxer.hikari.HikariConfig=DEBUG
logging.level.com.zaxxer.hikari=TRACE

so that you can see the detailed reason for the JDBC connection failing; it won't be obvious in the "stdout" output; that level is detail is not shown there; you have to go look in the actual nacos log file (nacos.log). Once you add the tracing for Hikari, you can immediately see the exception in the log file about public key exchange not being enabled.

note that I also did stuff like make a docker file for nacos that includes net-tools and bind-utils; thinking maybe some DNS resolver libraries were missing, and that's why hostname lookup would fail, and then JDBC wouldn't be able to connect...but that's completely unncessary; the base CentOS image works fine for DNS resolution even within Docker. Main issue I found was the public key exchange not being enabled.

yexiaobai commented 1 year ago

MYSQL_SERVICE_HOST=mysql 这里要写 mysql 服务的host,不能写 127.0.0.1 或者 localhost ;如果你测试能用(我跑通懒得测了),可以评论区告诉我修改。 我把mysql的地址127.0.0.1改成外网地址就没报java.lang.IllegalStateException: No DataSource set这个错误。 特么的,好心累。 前提是对应版本的建表sql是对的。

wangtianmin1202 commented 1 year ago

破案了,数据库的表要自己先建好.

minamike789 commented 1 year ago

错误原因:DB到期被锁了

snowwolf007cn commented 1 year ago

看下image里面的Dockerfile:

FROM mysql:8.0.31
ADD https://raw.githubusercontent.com/alibaba/nacos/develop/distribution/conf/mysql-schema.sql /docker-entrypoint-initdb.d/nacos-mysql.sql
RUN chown -R mysql:mysql /docker-entrypoint-initdb.d/nacos-mysql.sql
EXPOSE 3306
CMD ["mysqld", "--character-set-server=utf8mb4", "--collation-server=utf8mb4_unicode_ci"]

这里只是把sql文件拷贝下来了,并且给了可执行权限,但是并没有执行这个sql。 我开始很奇怪,因为我启动完数据库镜像以后,数据库里面的数据库nacosdev_test是存在的,我以为是执行了sql,后来我看这个sql的时候,并没有看到创建数据库的语句,因为,数据库的创建是跟着配置数据库镜像的时候自动创建的。即

MYSQL_DATABASE=nacos_devtest
MYSQL_USER=nacos
MYSQL_PASSWORD=nacos

这三行创建的

所以,从mysql容器bash进去,用mysql客户端以用户nacos连接服务器后,执行

use nacosdev_test;
source /docker-entrypoint-initdb.d/nacos-mysql.sql

在数据库里创建好所有表就可以了。

另外,这个"No datasource set"的异常信息,的确需要修改一下,完全看不出来是哪里的问题。

nightstream commented 8 months ago

2024年了,官方docker镜像还是不能自动建表,愁死

lixiang1991 commented 8 months ago

2024年了,官方docker镜像还是不能自动建表,愁死

研究了半天原来是这个原因

hujingguang commented 8 months ago

已经找了一个小时了,还没找到nacos-mysql.sql初始化数据库的sql在哪。。

https://raw.githubusercontent.com/alibaba/nacos/develop/distribution/conf/mysql-schema.sql

yuchao-su commented 2 months ago

2.4.2版本,同样的问题。总结如下: 1.MYSQL_SERVICE_HOST=mysql 这里注意mysql地址不能是localhost,是对于nacos容器的ip地址 2.mysql数据库要先执行初始化脚本(这个问题这么久了,官方竟然还没有解决)