docker-compose wordpress mysql connection refused

Harry picture Harry · Dec 3, 2015 · Viewed 34.2k times · Source

I've created a small docker-compose.yml which used to work like a charm to deploy small WordPress instances. It looks like this:

wordpress:
  image: wordpress:latest
  links:
   - mysql
  ports:
   - "1234:80"
  environment:
    WORDPRESS_DB_USER: wordpress
    WORDPRESS_DB_NAME: wordpress
    WORDPRESS_DB_PASSWORD: "password"
    WORDPRESS_DB_HOST: mariadb
    MYSQL_PORT_3306_TCP: 3306
  volumes:
    - /srv/wordpress/:/var/www/html/
mysql:
  image: mariadb:latest
  mem_limit: 256m
  container_name: mariadb
  environment:
    MYSQL_ROOT_PASSWORD: "password"
    MYSQL_DATABASE: wordpress
    MYSQL_USER: wordpress
    MYSQL_PASSWORD: "password"
  volumes:
    - /srv/mariadb:/var/lib/mysql

But when I start it now (maybe since docker update to Docker version 1.9.1, build a34a1d5), it fails

wordpress_1 | Warning: mysqli::mysqli(): (HY000/2002): Connection    refused in - on line 10
wordpress_1 | 
wordpress_1 | MySQL Connection Error: (2002) Connection refused

When I cat /etc/hosts of the wordpress_1 there are entries for MySQL:

172.17.0.10 mysql 12a564fdbc56 mariadb

and I am able to ping the MariaDB server.

When I docker-compose up, WordPress gets installed and after several restarts the MariaDB container prints:

Version: '10.0.22-MariaDB-1~jessie'  socket: '/var/run/mysqld/mysqld.sock'  port: 3306  mariadb.org binary distribution

Which schould indicate it to be running, isn't it?

How do I get the WordPress to be able to connect to the MariaDB container?

Answer

Mohamed Salem Lamiri picture Mohamed Salem Lamiri · Nov 14, 2016

To fix this issue the first thing to do is:

Add the following code to wordpress & database containers (in the docker-compose file):

restart: unless-stopped

This will make sure you Database is started and intialized before wordpress container trying to connect to it. Then restart docker engine

sudo restart docker

or (for ubuntu 15+)

sudo service docker restart 

Here the full configuration that worked for me, to setup wordpress with MariaDB:

version: '2'

services:
  wordpress:
    image: wordpress:latest
    links:
      - database:mariadb
    environment:
      - WORDPRESS_DB_USER=wordpress
      - WORDPRESS_DB_NAME=mydbname
      - WORDPRESS_TABLE_PREFIX=ab_
      - WORDPRESS_DB_PASSWORD=password
      - WORDPRESS_DB_HOST=mariadb
      - MYSQL_PORT_3306_TCP=3306
    restart: unless-stopped
    ports:
      - "test.dev:80:80"
    working_dir: /var/www/html
    volumes:
     - ./wordpress/:/var/www/html/
  database:
   image: mariadb:latest
   environment:
     - MYSQL_ROOT_PASSWORD=password
     - MYSQL_DATABASE=mydbname
     - MYSQL_USER=wordpress
     - MYSQL_PASSWORD=password
   restart: unless-stopped
   ports:
     - "3306:3306"