You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Docker-Compose中本地数据库无法映射MySQL镜像卷致表不存在问题

Fixing "Table 'data.token' doesn't exist" Error in Docker Compose Setup

Let's break down what's going wrong here and fix it step by step:

1. Incorrect MySQL Data Volume Path

Your current volume maps my-db to /usr/local/var/mysql—that’s the default path for local macOS MySQL installs, not the official MySQL Docker image. The official MySQL image stores its data at /var/lib/mysql. This mismatch means your local data isn’t being mounted into the container at all, so the container starts with a fresh, empty database.

2. Misplaced restart Directive

The restart: always line is nested inside the environment block, which is invalid YAML syntax for Docker Compose. It should be a top-level key under the db service.

3. Mismatched Database Name in Spring Configuration

You configured MySQL to create a database named tel, but your Spring app is trying to connect to a database called data (from jdbc:mysql://db/data). That’s why it’s looking for data.token instead of the expected tel.token.


Corrected Docker Compose File

db:
  image: mysql:latest
  environment:
    MYSQL_DATABASE: 'tel'
    MYSQL_USER: 'root'
    MYSQL_ROOT_PASSWORD: 'test'
  restart: 'always'  # Moved to top-level service configuration
  ports:
    - '3306:3306'
  volumes:
    - my-db:/var/lib/mysql  # Updated to official MySQL data directory path
app:
  image: "myapp/app:v1"
  ports:
    - "9292:9292"
  environment:
    SPRING_DATASOURCE_URL: jdbc:mysql://db/tel  # Matches the MySQL database name we created
    SPRING_DATASOURCE_USERNAME: root
    SPRING_DATASOURCE_PASSWORD: 'test'
  depends_on:
    - db
volumes:
  my-db:

Extra Tips

  • If you need to import your existing local data table into the container’s database, run these commands after starting the stack:
    # Copy your local SQL dump into the running MySQL container
    docker cp /path/to/your/local/dump.sql $(docker ps -q --filter name=db):/tmp/dump.sql
    # Import the dump into the 'tel' database
    docker exec -it $(docker ps -q --filter name=db) mysql -uroot -ptest tel < /tmp/dump.sql
    
  • Note that depends_on only ensures the db container starts before the app—it doesn’t wait for MySQL to finish initializing. For production setups, add a healthcheck to the db service to make Docker wait until MySQL is ready to accept connections.

内容的提问来源于stack exchange,提问作者Harsh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:26:16