Docker技术问题:如何让一个容器等待另一个容器加载完成?
Hey there! I’ve dealt with this exact issue countless times—getting backend services to hold off starting until databases are fully operational, not just up and running. Here are the two most reliable approaches for your setup:
Option 1: Use Docker Compose Healthchecks (Official & Recommended)
Docker Compose lets you define health checks for services, and you can configure your backend to only start once mysql is marked as healthy.
Update your docker-compose.yml with these changes:
version: "3" services: mysql: image: "my-mysql:latest" ports: - "3306:3306" environment: MYSQL_ROOT_PASSWORD: rootpw # Add health check to verify MySQL is ready to accept connections healthcheck: test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-u", "root", "-p${MYSQL_ROOT_PASSWORD}"] interval: 5s # Check connection status every 5 seconds timeout: 5s # Abort check if no response after 5 seconds retries: 5 # Retry up to 5 times before marking unhealthy start_period: 10s # Wait 10 seconds before first check (gives MySQL time to initialize) backend: image: "my-backend:latest" ports: - 19001:19001 - 80:80 - "9001:9000" environment: DB_USERNAME: test DB_PASSWORD: test DB_URL: jdbc:mysql://mysql:3306/test?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&verifyServerCertificate=false&useSSL=true jdbc_url: jdbc:mysql://mysql:3306 # Make backend wait for MySQL to pass its health check depends_on: mysql: condition: service_healthy
How this works:
- The
healthcheckon themysqlservice runsmysqladmin pingto confirm the database accepts connections. - The
backendservice will hold off starting until themysqlservice passes its health check (after the initial start period and successful retries).
Option 2: Use a Wait Script (For Custom Readiness Checks)
If you need more control—like verifying a specific database or table exists—you can use a script like wait-for-it.sh or wait-for in your backend container.
- First, add the
wait-for-it.shscript to your backend image (bundling it into the image is more reliable than mounting via a volume). - Update the
backendservice's command to run the script before starting your app:
backend: # ... existing config ... command: ["./wait-for-it.sh", "mysql:3306", "--timeout=30", "--", "java -jar your-backend-app.jar"]
Note:
wait-for-it.shwaits until the specified host:port is reachable. You can extend it to run a SQL query (like checking if thetestdatabase exists) for stricter readiness validation.
Important Reminder
The default depends_on without a condition only waits for the mysql container to start—not for the MySQL service to be fully ready. That’s why you need either health checks or a wait script to avoid early connection errors in your backend.
内容的提问来源于stack exchange,提问作者Joe

