Docker部署WordPress+Nginx及HTTPS配置:MySQL连接拒绝问题排查
Hey there! Let's break down your two questions—first fixing that annoying MySQL connection error you're stuck on, then walking through a complete HTTPS-enabled setup with Docker, WordPress, and Nginx.
First: Fixing the "MySQL Connection Error: (2002) Connection refused"
That error almost always boils down to one of three things: your WordPress container is starting before MySQL is ready, the services aren't on the same network, or there's a misconfiguration in your environment variables. Let's fix each potential issue step by step.
1. Ensure WordPress waits for MySQL to be fully ready
Right now, your docker-compose.yml doesn't enforce a startup order. WordPress tries to connect before MySQL has finished initializing, hence the "connection refused" error. Let's add a health check to MySQL and make WordPress depend on it.
Update your db service with a health check:
db: image: mysql:5.7 volumes: - db_data:/var/lib/mysql restart: always environment: MYSQL_ROOT_PASSWORD: somewordpress MYSQL_DATABASE: wordpress MYSQL_USER: wordpress MYSQL_PASSWORD: wordpress # Add this health check to verify MySQL is up healthcheck: test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-u", "wordpress", "-p${MYSQL_PASSWORD}"] interval: 10s timeout: 5s retries: 5
Then update your wordpress service to wait for MySQL's health check to pass:
wordpress: container_name: wordpress image: wordpress:php7.4-apache restart: always stdin_open: true tty: true # Wait for MySQL to be healthy before starting depends_on: db: condition: service_healthy environment: WORDPRESS_DB_HOST: db:3306 WORDPRESS_DB_USER: wordpress WORDPRESS_DB_PASSWORD: wordpress WORDPRESS_DB_NAME: wordpress volumes: - ./wordpress:/var/www/html
2. Explicitly define a shared network
While Docker Compose creates a default network for your services, explicitly defining one avoids any weird network isolation issues. Add this to the bottom of your docker-compose.yml:
volumes: db_data: # Add shared network networks: wp-network: driver: bridge
Then add the networks field to each service (db, wordpress, nginx):
# Example for db service (repeat for wordpress and nginx) db: ... networks: - wp-network
3. Verify MySQL is running correctly
If the above doesn't fix it, double-check that MySQL is actually up and accepting connections. Run:
docker-compose exec db mysql -u wordpress -pwordpress
If you can log into the MySQL shell, your database is fine—any remaining issue is with WordPress's connection settings (which look correct in your config, so the health check fix should resolve it).
Second: Complete HTTPS-Enabled Docker + WordPress + Nginx Setup
Now that we've fixed the connection error, let's build out the full HTTPS setup. Here's a production-ready configuration:
1. Local Directory Structure
First, create these folders on your host machine:
mkdir -p wp-project/{wordpress,nginx/conf,certs} cd wp-project
2. Full docker-compose.yml
This config includes HTTPS support, proper service dependencies, and shared networking:
version: "3.8" services: db: image: mysql:5.7 volumes: - db_data:/var/lib/mysql restart: always environment: MYSQL_ROOT_PASSWORD: somewordpress MYSQL_DATABASE: wordpress MYSQL_USER: wordpress MYSQL_PASSWORD: wordpress healthcheck: test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-u", "wordpress", "-p${MYSQL_PASSWORD}"] interval: 10s timeout: 5s retries: 5 networks: - wp-network wordpress: container_name: wordpress image: wordpress:php7.4-apache restart: always stdin_open: true tty: true depends_on: db: condition: service_healthy environment: WORDPRESS_DB_HOST: db:3306 WORDPRESS_DB_USER: wordpress WORDPRESS_DB_PASSWORD: wordpress WORDPRESS_DB_NAME: wordpress # Force WordPress to use HTTPS for admin and detect reverse proxy WORDPRESS_CONFIG_EXTRA: | define('FORCE_SSL_ADMIN', true); if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') { $_SERVER['HTTPS'] = 'on'; } volumes: - ./wordpress:/var/www/html networks: - wp-network nginx: container_name: nginx image: nginx:latest restart: unless-stopped ports: - 80:80 - 443:443 volumes: - ./nginx/conf:/etc/nginx/conf.d - ./certs:/etc/nginx/certs # Mount your SSL certificates here - ./wordpress:/var/www/html:ro # Read-only access to WordPress files depends_on: - wordpress networks: - wp-network volumes: db_data: networks: wp-network: driver: bridge
3. Nginx HTTPS Reverse Proxy Config
Create ./nginx/conf/wp.conf with this content (replace your-domain.com with your actual domain):
# Redirect HTTP to HTTPS server { listen 80; server_name your-domain.com; return 301 https://$host$request_uri; } # HTTPS Server Block server { listen 443 ssl; server_name your-domain.com; # Path to your SSL certificates ssl_certificate /etc/nginx/certs/fullchain.pem; ssl_certificate_key /etc/nginx/certs/privkey.pem; # Secure SSL settings ssl_protocols TLSv1.2 TLSv1.3; ssl_ciphers HIGH:!aNULL:!MD5; root /var/www/html; index index.php index.html index.htm; # Handle WordPress permalinks location / { try_files $uri $uri/ /index.php?$args; } # Pass PHP requests to WordPress container location ~ \.php$ { fastcgi_pass wordpress:80; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } # Block access to .htaccess files location ~ /\.ht { deny all; } }
4. Get SSL Certificates
- Production: Use Let's Encrypt with Certbot to get free, trusted certificates. Place the
fullchain.pemandprivkey.pemfiles in the./certsfolder. - Testing: Generate a self-signed certificate with this command:
openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout ./certs/privkey.pem -out ./certs/fullchain.pem
5. Start the Services
Run this command to start everything in the background:
docker-compose up -d
Once all containers are running, visit https://your-domain.com to complete the WordPress installation.
Quick Tips
- Permissions: On Linux, make sure the
./wordpressfolder has the correct ownership for the WordPress container:chown -R www-data:www-data ./wordpress - Backups: Regularly back up the
./wordpressdirectory and thedb_datavolume to avoid data loss. - Troubleshooting: If Nginx isn't working, check its logs with
docker-compose logs nginx.
内容的提问来源于stack exchange,提问作者glardz876

