请教在宝塔中使用docker-compose部署new-api 连接宿主机中的mysql和redis

mysql 5.7.44

如题,各位大佬 我在宝塔中 使用 docker-compose.yml 部署,(已经新建了mysql数据库 newapi)
不想用公网ip,尝试localhost,127.0.0.1 172.21.0.1 host.docker.internal 都不行 报错,请问下我这个应该如何配置哈,
尝试在mysql内 执行命令对新建的newapi 用户授权%
宝塔安全 开放指定ip 公网ip 172.21.0.0/16 3306 端口进入也不行

version: '3.4'

services:
  new-api:
    image: calciumion/new-api:latest
    # build: .
    container_name: new-api
    restart: always
    command: --log-dir /app/logs
    ports:
      - "3000:3000"
    volumes:
      - ./data:/data
      - ./logs:/app/logs
    environment:
       - SQL_DSN=newapi:eXGafmSfLWD8nbE3@tcp(localhost:3306)/new-api
       - REDIS_CONN_STRING=redis://localhost:6379/1
      # - SESSION_SECRET=pV9kLB4rx2z6yPB8Vw67bLWdaaoFMebM
      - TZ=Asia/Shanghai
#      - NODE_TYPE=slave  # 多机部署时从节点取消注释该行
#      - SYNC_FREQUENCY=60  # 需要定期从数据库加载数据时取消注释该行
#      - FRONTEND_BASE_URL=https://openai.justsong.cn  # 多机部署时从节点取消注释该行
    healthcheck:
      test: [ "CMD-SHELL", "wget -q -O - http://localhost:3000/api/status | grep -o '\"success\":\\s*true' | awk -F: '{print $2}'" ]
      interval: 30s
      timeout: 10s
      retries: 3


各种测试的报错信息 

这条 配置以下报错SQL_DSN=mysql://newapi:wRXppDZpiMRCzDs7@tcp(localhost:3306)/newapi?parseTime=true

2024/11/16 01:29:31 e[35m/build/model/main.go:75
e[0me[31m[error] e[0mfailed to initialize database, got error dial tcp [::1]:3306: connect: connection refused
[FATAL] 2024/11/16 - 01:29:31 | [dial tcp [::1]:3306: connect: connection refused]
SQL_DSN=mysql://newapi:wRXppDZpiMRCzDs7@tcp(172.21.0.1:3306)/newapi?parseTime=true

2024/11/16 01:30:37 e[35m/build/model/main.go:75
e[0me[31m[error] e[0mfailed to initialize database, got error Error 1130: Host '172.21.0.2' is not allowed to connect to this MySQL server
[FATAL] 2024/11/16 - 01:30:37 | [Error 1130: Host '172.21.0.2' is not allowed to connect to this MySQL server]
SQL_DSN=mysql://newapi:wRXppDZpiMRCzDs7@tcp(host.docker.internal:3306)/newapi?parseTime=true

2024/11/16 01:31:33 e[35m/build/model/main.go:75
e[0me[31m[error] e[0mfailed to initialize database, got error dial tcp: lookup host.docker.internal on 127.0.0.11:53: no such host
[FATAL] 2024/11/16 - 01:31:33 | [dial tcp: lookup host.docker.internal on 127.0.0.11:53: no such host]

查看mysql里面的权限

10 个赞

请教各位大佬,如何在不配置公网ip 或者不外泄3306 端口情况下 配置好 mysql 和redis

mysql和redis 是宝塔 安装的 new-api 是docker-compose 使用这个方便管理升级

不使用sqlite,用mysql是想可以直接连数据库动态添加key 渠道

network_mode: host

使用host网络类型,默认是docker的网络,此时localhost是指的docker 实例本身,

切换为host模式后,端口是直接启动在宿主机上,此时localhost就是宿主机

加上以下设置:

extra_hosts:
      - "host.docker.internal:host-gateway"

然后再使用 host.docker.internal 试试?

宝塔中找到那个容器,加一个网段,带bt的,然后就可以直接通过http://容器名称:容器里的ip就好了