B
B
bernex2016-08-18 16:48:58
Docker
bernex, 2016-08-18 16:48:58

How to set up a connection to the database on the host from the container?

Configured nginx and php via docker-compose.yml
How to make php able to connect to local database?

version: '2'
services:
    web:
        build:
            context: ./
            dockerfile: web.docker
        volumes:
            - ./:/var/www
        ports:
            - "8080:80"
        links:
            - app
    app:
        build:
            context: ./
            dockerfile: app.docker
        volumes:
            - ./:/var/www

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
Tyranron, 2016-08-19
@Tyranron

Pass the host, login and password to the app container through environment variables to access the database. In the app code, take the database connection parameters from the forwarded environment variables.
Or, mount a folder with a unix database socket in volumes and connect to this socket in the app code. But this will only work when the db and app are strictly on the same machine.

H
hacker2001, 2018-08-22
@hacker2001

The simplest solution is `docker run --network host...` or add to `docker-compose.yml`:

version: '3'

services:
  myservice:
    // ...
    network_mode: host

For a variety of reasons, these solutions may not suit us. Next, I will describe another solution.
So, first we need to find out our local ip address:
$ hostname -I | cut -d ' ' -f1
192.168.0.82

Next, you need to get the path to the config file:
$ psql
psql (10.5 (Ubuntu 10.5-0ubuntu0.18.04))
Type "help" for help.

sergey=# SHOW config_file;
               config_file               
-----------------------------------------
 /etc/postgresql/10/main/postgresql.conf
(1 row)

sergey=# \q

Then add the local IP to the list of listening addresses:
It should turn out something like this:
#------------------------------------------------------------------------------
# CONNECTIONS AND AUTHENTICATION
#------------------------------------------------------------------------------

# - Connection Settings -

listen_addresses = 'localhost,192.168.0.82'  # можно просто звездочку (*) напечатать

At the end of `/etc/postgresql/10/main/hba_conf.conf` you need to add the line:
This will avoid errors like:
Restart Postgres:
And then in the scripts, instead of localhost, we specify the local IP address.
The instruction is here
The described method is also suitable for mysql: you need the mysql server to listen to host 0.0.0.0

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question