I have a MySQL server on my host machine and I want my docker containers connect to it, instead of create a MySQL container.
In my application configuration file I'm using localhost, as I used to do before using Docker, but the connection is being refused.
I'm using docker-compose and here is my .yml:
version: "3.2"
services:
    php:
        build: 
            context: './dockerfiles/php/'
            args:
                PHP_VERSION: ${PHP_VERSION}
        networks:
            - backend
        volumes:
            - ${PROJECT_ROOT}/:/var/www/html/
        container_name: acadbase_php
    apache:
        build:
            context: './dockerfiles/apache/'
            args:
                APACHE_VERSION: ${APACHE_VERSION}
        depends_on:
            - php
        networks:
            - frontend
            - backend
        ports:
            - "8080:80"
        volumes:
            - ${PROJECT_ROOT}/:/var/www/html/
        container_name: acadbase_apache
networks:
    frontend:
    backend:
volumes:
    data:
My ./dockerfiles/php/Dockerfile:
ARG PHP_VERSION=""
FROM php:${PHP_VERSION:+${PHP_VERSION}-}fpm-alpine
RUN apk update; \
    apk upgrade; \
    apk add libxml2-dev
RUN docker-php-ext-install mysqli soap mbstring xml pdo_mysql
My  ./dockerfiles/apache/Dockerfile:
ARG APACHE_VERSION=""
FROM httpd:${APACHE_VERSION:+${APACHE_VERSION}-}alpine
RUN apk update; \
    apk upgrade; \
    apk add vim;
COPY acadbase.conf /usr/local/apache2/conf/acadbase.conf
RUN echo "Include /usr/local/apache2/conf/acadbase.conf" \
    >> /usr/local/apache2/conf/httpd.conf
My .env:
PHP_VERSION=7.1
APACHE_VERSION=2.4
PROJECT_ROOT=.
                As @StrahinjaTasic and @AvinashReddy said, I need to use the IP of my host machine, but it was not working only because I needed to do more things in my MySQL local server.
1- I needed to allow the database user connects from the container IP (or from everywhere) instead of only from localhost.
# use the correct IP if it is not for local development
GRANT ALL PRIVILEGES ON *.* TO '[user]'@'%';
FLUSH PRIVILEGES;
For MySQL GRANT command details see: https://dev.mysql.com/doc/refman/5.7/en/grant.html
2- I needed to change MySQL configuration file to let it listen not only localhost, but also the container IP (or everywhere).
In my case, the configuration file is /etc/mysql/mysql.conf.d/mysqld.conf.
# use the correct IP if it is not for local development
bind-address = 0.0.0.0
After that I put the IP of my host machine and my database user credentials in my application configuration file and it worked!
P.S.: To get the container IP see How to get a Docker container's IP address from the host?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With