Node.js(NestJS)应用Docker化后无法连接MySQL数据库求助
Hey there, I see exactly where the issue is here—let's get your setup working properly!
The Core Problem: Incorrect Database Host
Your TypeORM config uses localhost as the database host, but inside your NestJS Docker container, localhost refers to the container itself, not the MySQL container running alongside it.
In Docker Compose, containers on the same network can communicate using the service name you defined in your docker-compose.yml. Since your MySQL service is named db, that's the hostname you need to use instead of localhost.
Step 1: Update TypeORM Configuration
Modify your TypeORM config to use db as the host, and adjust the entities path if you're running compiled JS in Docker:
{ "type": "mysql", "host": "db", // Changed from localhost "port": 3306, "username": "root", "password": "root", "database": "nest", "entities": ["dist/**/*.entity{.ts,.js}"], // Use dist instead of src for compiled code "synchronize": true }
Side note: If your NestJS app is compiled to JavaScript (standard for Docker images), the entities path needs to point to the dist folder instead of src—this is a super common gotcha!
Step 2: Fix Docker Compose (Wait for MySQL to Be Ready)
Your current depends_on only ensures the db service starts before your NestJS app, but it doesn't wait for MySQL to finish initializing and be ready to accept connections. This often causes connection errors on first startup.
Add a health check to the MySQL service and update the dependency condition to wait for it to be healthy:
version: "3" services: db: image: mysql restart: always environment: MYSQL_ROOT_PASSWORD: root MYSQL_DATABASE: nest MYSQL_USER: root MYSQL_PASSWORD: root networks: - new healthcheck: test: ["CMD", "mysqladmin", "ping", "-h", "localhost"] timeout: 20s retries: 10 nest: image: grimscythe/nest-sample depends_on: db: condition: service_healthy # Wait until MySQL is fully ready ports: - 3000:3000 networks: - new networks: new:
Step 3: Quick Network Verification
To confirm connectivity between containers, run this command to ping the MySQL service from your NestJS container:
docker exec -it <your-nest-container-name> ping db
If it pings successfully, your network setup is working as expected.
Final Checks
- Double-check your NestJS Docker image ensures dependencies are installed and the app is compiled (if using a Dockerfile, make sure it runs
npm installandnpm run buildbefore starting the app). - Confirm MySQL credentials in TypeORM config match exactly what's in
docker-compose.yml(yours look correct, but it never hurts to verify!).
Once you make these changes, restart your services with docker-compose down && docker-compose up --build and your NestJS app should connect to MySQL without issues.
内容的提问来源于stack exchange,提问作者Damian Chrzanowski

