1
votes

Got a Laravel 5.8 application spun up locally on Docker.

I can run the app on my browser, connect to the database on Sequel Pro, but when I try and migrate the database, I get the dreaded [2002] Connection refused error.

I have set the mysql port to 3307 as I have another mysql container using 3306 for a different project. I don't want to have to keep stopping and starting docker for each project as I might be flicking between the 2 regularly, that's why I'm using different ports.

Here is the mysql section in the docker-compose file.

mysql:
    image: mysql:5.7
    ports:
      - "3307:3306"
    environment:
      MYSQL_HOST: 127.0.0.1
      MYSQL_ROOT_PASSWORD: secret
      MYSQL_DATABASE: forecast
      MYSQL_USER: forecast
      MYSQL_PASSWORD: secret
    volumes:
      - mysql:/var/lib/mysql
    networks:
      - forecast

Here is my .env file DB set up keys

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3307
DB_DATABASE=forecast
DB_USERNAME=forecast
DB_PASSWORD=secret

Also worth noting I am running the app on port 81, instead of 80 for the same reason. In my browser, I have to put {domain.testing}:81 which works.

3

3 Answers

3
votes

I have figured this out for anyone having the same problem.

I had to adjust my .env file.

DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=3306
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret

So I changed the DB_HOST to mysql and the DB_PORT back to 3306 as docker maps it to 3307. Then it worked successfully.

1
votes

change DB_HOST=127.0.0.1 to DB_HOST=mysql and it should work. Because in container network your host is mysql not 127.0.0.1.

And also because of port forwarding there is no need to change .env 3306 to 3307. docker will do based on network settings. Leave it as DB_PORT=3306

0
votes

Change 127.0.0.1 to mysql

mysql:
    image: mysql:5.7
    ports:
      - "3307:3306"
    environment:
      MYSQL_HOST: mysql
      MYSQL_ROOT_PASSWORD: secret
      MYSQL_DATABASE: forecast
      MYSQL_USER: forecast
      MYSQL_PASSWORD: secret
    volumes:
      - mysql:/var/lib/mysql
    networks:
      - forecast