3

Rather than having the MySQL database in Docker, or in a separate volume, I'd like Docker to connect to my pre-existing MySQL database I have running locally.

I'm using Laravel, hence the environment variables.

Can anyone help?

This is my docker-compose.yml file:

version: '2'

services:
    web:
        image: nginx:latest
        ports:
            - "8080:80"
        volumes:
            - .:/code
            - .docker/nginx.conf:/etc/nginx/conf.d/default.conf
    php:
        build:
            context: .
            dockerfile: .docker/Dockerfile
        image: php:7-fpm
        volumes:
            - .:/code
        environment:
            DB_CONNECTION: mysql
            DB_PORT: 3306
            DB_HOST: mysql
            DB_DATABASE: website_development
            DB_USERNAME: website_username
            DB_PASSWORD: website_pA$£w0r6
            REDIS_HOST: redis
            SESSION_DRIVER: redis
            CACHE_DRIVER: redis
    mysql:
        image: mysql:5.7
        ports:
            - 13306:3306
        environment:
            MYSQL_DATABASE: website_development
            MYSQL_USER: website_username
            MYSQL_PASSWORD: website_pA$£w0r6
            MYSQL_ROOT_PASSWORD: root_pA$£w0r6
    redis:
        image: redis:4.0-alpine
        ports:
            - 16379:6379
Ben Rolfe
  • 439
  • 5
  • 8
  • What do you mean by `Docker to connect to my pre-existing MySQL`? – matino Feb 21 '18 at 14:47
  • 1
    You don't need the mysql service. You don't want to start a mysql container. I assume you have a MySQL running locally on 3360 with the right user/passwd/db etc. You'll only need to adapt the DB_CONNECTION value and point to your local IP like 192.168.xx.xx (not localhost!). Or for mac you can use: `docker.for.mac.localhost` as host – lvthillo Feb 21 '18 at 15:03

2 Answers2

2

You are starting a new mysql docker container, which is not needed as can be inferred from you question. Thus the mysql service part should be removed from you composefile.

You question now reduces to how to connect from the container to the database running on the local machine. This question has been answered thoroughly in From inside of a Docker container, how do I connect to the localhost of the machine? and the way to do that depends on the OS of the machine where docker is running.

yamenk
  • 46,736
  • 10
  • 93
  • 87
1

If you remove the mysql service which is creating a MySQL container, you can just change the env vars to point to your local instance.

On a mac, this can be done by connecting to docker.for.mac.localhost or docker.for.mac.host.internal, though the latter is now preferred.

Arlo Clarke
  • 315
  • 2
  • 10