Manu
Manu

Reputation: 51

How to access the database running in a docker container from the same wordpress server(docker container running in same server)?

I have a WordPress server and it's trying to connect the database which is running as a docker container locally. But while accessing localhost:80 getting "Error establishing a database connection" error

i have a database container running

CONTAINER ID   IMAGE       COMMAND                  CREATED          STATUS          PORTS                 NAMES
9f9fea1b744e   mysql:5.7   "docker-entrypoint.s…"   47 minutes ago   Up 47 minutes   3306/tcp, 33060/tcp   my_mysql

And am trying to configure it in WordPress file /var/www/html/wp-config.php like this

define( 'DB_NAME', 'wordpress' );^M
^M
/** MySQL database username */^M
define( 'DB_USER', 'root' );^M
^M
/** MySQL database password */^M
define( 'DB_PASSWORD', '****' );^M
^M
/** MySQL hostname */^M
define( 'DB_HOST', 'mysql:3306' );^M

Upvotes: 0

Views: 1861

Answers (1)

BertC
BertC

Reputation: 2666

Both WP and DB in a Container

With the following docker-compose.yml file you'll have Wordpress and Database running each in its own docker container:

version: '3.1'

services:

  wordpress:
    image: wordpress
    restart: always
    ports:
      - 8181:80
    environment:
      WORDPRESS_DB_HOST: db
      WORDPRESS_DB_USER: exampleuser
      WORDPRESS_DB_PASSWORD: examplepass
      WORDPRESS_DB_NAME: exampledb
    volumes:
      - ./wp:/var/www/html

  db:
    image: mysql:5.7
    restart: always
    environment:
      MYSQL_DATABASE: exampledb
      MYSQL_USER: exampleuser
      MYSQL_PASSWORD: examplepass
      MYSQL_RANDOM_ROOT_PASSWORD: '1'
    volumes:
      - db:/var/lib/mysql
    ports:
      - "8086:3306"

volumes:
  db:

For the WP in the Container your database is running on host 'db' and on port '3306'.

WP on the Host and DB in the Container

To access the Database running in the above container from a WP running on the host, your database is running on host 'localhost' and on port '8086'

Upvotes: 1

Related Questions