Intermittent "Error establishing a database connection" errors with WordPress on Docker, when using an external network

I'm trying to set up a simple installation of Wordpress using Docker. The Docker Compose file from the official image page works fine, but when I modify it as follows to connect to an external network (which I want to do in order to use an existing caddy-docker-proxy container as a reverse proxy), I get intermittent "Error establishing a database connection" errors: version: '3.1' services: wordpress: image: wordpress restart: always ports: - 8080:80 environment: WORDPRESS_DB_HOST: db WORDPRESS_DB_USER: exampleuser WORDPRESS_DB_PASSWORD: ******** WORDPRESS_DB_NAME: exampledb volumes: - wordpress:/var/www/html networks: caddy: ipv4_address: 172.16.0.30 db: image: mysql:8.0 restart: always environment: MYSQL_DATABASE: exampledb MYSQL_USER: exampleuser MYSQL_PASSWORD: ******** MYSQL_RANDOM_ROOT_PASSWORD: '1' volumes: - db:/var/lib/mysql networks: caddy: ipv4_address: 172.16.0.31 volumes: wordpress: db: networks: caddy: external: true The maddening thing is that while these errors seem to appear on many or most page loads, it often does work fine, and I can get all the way through a basic installation by just tediously refreshing the page every time I see the error. The system is a cheap cloud VM, very lightly loaded. I've looked at the Wordpress and and database logs, but have not found anything. What could the problem be? How can I troubleshoot this further?

Comment (1)

Jese Leos

September 14, 2024

Verified user

Use depends_on in your Docker file so that WordPress starts only after the database is ready. In this code snippet: wordpress: image: wordpress restart: always depends_on: - db ports: - 8080:80 environment: WORDPRESS_DB_HOST: db WORDPRESS_DB_USER: exampleuser WORDPRESS_DB_PASSWORD: ******** WORDPRESS_DB_NAME: exampledb volumes: - wordpress:/var/www/html networks: caddy: ipv4_address: 172.16.0.30 By doing this, it should improve the communication between the database and your application, as WordPress will depend on the database's availability to start. I'm not sure about your internal DB configuration, but check if the my.cnf in this Docker is set for more connections according to your application's demand, under max_connections.

You’ll be in good company