Docker-Compose部署WordPress+MariaDB+Nginx遇数据库连接错误求助
Hey there, let's sort out this database connection error you're facing. The main culprit here is a mismatched database hostname in your WordPress Docker configuration—let's break this down and fix it right away.
The Root Cause
Looking at your docker-compose.yml, your MariaDB service is named mariadb, but your WordPress service is configured to connect to db:3306 via the WORDPRESS_DB_HOST environment variable. In Docker Compose, services communicate using their service names as hostnames. Since there's no service named db in your setup, WordPress can't reach the MariaDB instance, hence the connection error.
Step 1: Update the WordPress Database Host
Modify the WORDPRESS_DB_HOST value in your docker-compose.yml for the WordPress service to use the correct service name (mariadb):
wordpress: container_name: wordpress image: wordpress:fpm-alpine depends_on: - mariadb volumes: - ./wordpress:/var/www/html environment: WORDPRESS_DB_HOST: mariadb:3306 # Changed from db:3306 to mariadb:3306 WORDPRESS_DB_USER: wordpress WORDPRESS_DB_PASSWORD: wordpress WORDPRESS_DB_NAME: wordpress restart: always
Step 2: Restart Your Services
After making the change, bring down and restart your containers to apply the new configuration:
docker-compose down docker-compose up -d
Additional Troubleshooting (If Issues Remain)
If you still see the error after the fix, try these checks:
- Check if MariaDB is running: Run
docker-compose psto confirm themariadbcontainer is in theUpstate. If it's restarting or stopped, check its logs withdocker-compose logs mariadbfor issues like volume permission errors. - Verify volume permissions: Ensure the
./mariadband./wordpressdirectories on your host have proper write permissions for the containers. For Alpine-based images, you may need to set ownership tomysql(for MariaDB) orwww-data(for WordPress). - Test network connectivity: Exec into the WordPress container and ping the MariaDB service to confirm they can communicate:
If the ping works, the network is solid—double-check that your database credentials (user, password, database name) match exactly between MariaDB and WordPress.docker-compose exec wordpress ping mariadb
内容的提问来源于stack exchange,提问作者nalmo

