Docker-Compose中本地数据库无法映射MySQL镜像卷致表不存在问题
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
datatable 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_ononly ensures thedbcontainer starts before the app—it doesn’t wait for MySQL to finish initializing. For production setups, add a healthcheck to thedbservice to make Docker wait until MySQL is ready to accept connections.
内容的提问来源于stack exchange,提问作者Harsh

