简体   繁体   中英

Connect laravel container to existing mysql container via docker compose

I am new to docker, I am trying to connect the existing MySQL container to my Laravel application through docker-compose.

Where MySQL docker-compose.yml file is like

version: '3'

services:
  web:
    container_name: ${APP_NAME}_web
    build:
     context: ./docker/web
    ports:
      - "9000:80"
    volumes:
      - ./:/var/www/app
    depends_on:
      - db
  db:
    container_name: ${APP_NAME}_db
    image: mysql:5.7
    ports:
      - "3307:3306"
    restart: always
    volumes: 
      - dbdata:/var/lib/mysql/
    environment:
      - MYSQL_ROOT_PASSWORD=root
      - MYSQL_DATABASE=laravel_docker_db
volumes:
  dbdata:
    driver: local
    driver_opts:
       type: none
       device: /storage/docker/laravel_mysql_data
       o: bind

This script is downloading the latest mysql version and making a new container. I just want to connect MYSQL container with my application

Where my existing MYSQL container is created with a specific IP using a bridge network and running on docker-machine.

在此处输入图像描述

I am wondering, can I define the existing MYSQL container configurations on the db context ?

Try this docker-compose file:

version: '3.5'
services:
  db:
    container_name: myapp_db
    image: mysql:5.7
    ports:
      - "3307:3306"
    restart: always
    volumes:
      - dbdata:/var/lib/mysql/
    environment:
      - MYSQL_ROOT_PASSWORD=root
      - MYSQL_DATABASE=laravel_docker_db
    networks:
      - myapp-network

networks:
  myapp-network:
    driver: bridge

Situation has two cases: 1. If your laravel instance is in docker too - just add to.env file next rows:

DB_HOST=myapp_db
DB_PORT=3306
DB_DATABASE=laravel_docker_db
DB_USERNAME=root
DB_PASSWORD=root

2.If you don't use docker for laravel - just change variable DB_HOST=localhost

In.env file:

DB_HOST=db
DB_PORT=3306
DB_DATABASE=your database name
DB_USERNAME=root
DB_PASSWORD=root

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM