3

I have an Ubuntu 16.04 installation in a vm and I'm trying to run an app inside a docker container and connect it to a MySQL database on the host

I have something like this.. on the host I have the MySQL:

And when I try to connect my app to the MySQL I got this:

java.sql.exception: cannot create poolableConnectionFactory ( Could not create connection to database server. Attempted reconnect 3 times

I execute my app using a docker-compose:

version: '2'
services:
  exo:
    image: exoplatform/exo-community:5.0
    environment:
      EXO_DB_TYPE: mysql
      EXO_DB_NAME: user
      EXO_DB_USER: root
      EXO_DB_PASSWORD: "my-pass"
      EXO_DB_HOST: "127.0.0.1"
      EXO_ADDONS_LIST: exo-jdbc-driver-mysql
    expose:
      - "8080"
      - "3306"
    ports:
      - "8080:8080"
    volumes:
      - exo_data:/srv/exo
      - exo_logs:/var/log/exo
volumes:
  exo_data:
    external:
      name: exo_data
  exo_logs:
    external:
      name: exo_logs
networks:
  default:
      driver: bridge

As you can see I try to connect to the MySQL default port... And I just saw that 3306 port is listening on the host.

I also tried to add the following line ( saw on another post)

In my.cnf I have the bind-address 0.0.0.0.

And MySQL is running:

root@xxx/# mysqladmin -u root -p status

Uptime: 4784  Threads: 4  Questions: 17  Slow queries: 0  Opens: 114  Flush tables: 1  Open tables: 33  Queries per second avg: 0.003

I'm using docker on bridge so I guess I just need to add the port on docker composer in order to connect docker and host. But nothing seems to works. Can someone point me to right direction?

Blue
  • 22,608
  • 7
  • 62
  • 92
MarEng
  • 198
  • 2
  • 3
  • 12

2 Answers2

3

The problem is that you are trying to connect to the host from the container using localhost. This won't work as the container has its own ip and localhost will hit the container and not the host.

Connecting from container to host is a very frequent question on stackoverflow and you can find many answers in From inside of a Docker container, how do I connect to the localhost of the machine?

The easiest way (though not recommended) is to use network_mode: host inside docker-compose file. In this case, the container will share the networking with the host and localhost will hit the host machine as well.

yamenk
  • 46,736
  • 10
  • 93
  • 87
  • i just add the network_mode line to the composer file and everything starts working. This is just for tests, in a production environment we will use bridge perphaps. So thanks, you solved my problem! – MarEng Jan 26 '18 at 16:00
0

I think you need specify IP address:

mysql -u root -p -h 44.55.66.77

and give privileges for your:

DB GRANT ALL ON yourDatabase.* TO root@’1.2.3.4’ IDENTIFIED BY ‘my-pass’;

to get IP address inside container you can run this:

awk 'END{print $1}' /etc/hosts
qwertmax
  • 3,120
  • 2
  • 29
  • 42