I have Laravel running in Docker with 3 containers – Nginx, MySQL 8 And PHP 8.
I have the following docker-compose.yaml
version: '3.8' services: server: build: context: . dockerfile: dockerfiles/nginx.dockerfile ports: - '8000:80' volumes: - ./src:/var/www/html - ./nginx/nginx.conf:/etc/nginx/conf.d/default.conf:ro container_name: server depends_on: - app - db app: build: context: . dockerfile: dockerfiles/php.dockerfile volumes: - ./src:/var/www/html:delegated container_name: app db: image: mysql:8.0 env_file: - ./env/mysql.env container_name: db
This command:
docker-compose up -d server
Launches 3 containers:
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 5ff5cbefd12e toolkit_server "/docker-entrypoint.…" 9 seconds ago Up 3 seconds 0.0.0.0:8000->80/tcp server c7f3c9753909 toolkit_app "docker-php-entrypoi…" 14 seconds ago Up 8 seconds 9000/tcp app d7b421bd3c3b mysql:8.0 "docker-entrypoint.s…" 14 seconds ago Up 9 seconds 3306/tcp, 33060/tcp db
I want to run php artisan migrate
, so I try it like so:
docker-compose exec app php artisan migrate
This gives me the following error:
IlluminateDatabaseQueryException SQLSTATE[HY000] [2002] Connection refused (SQL: select * from information_schema.tables where table_schema = toolkit and table_name = migrations and table_type = 'BASE TABLE')
My mysql.env file is like so:
MYSQL_DATABASE=toolkit MYSQL_USER=root MYSQL_PASSWORD=password MYSQL_ROOT_PASSWORD=password
AND .env:
DB_CONNECTION=mysql DB_HOST=db DB_PORT=3306 DB_DATABASE=toolkit DB_USERNAME=root DB_PASSWORD=password
I’ve tried changing ports, host, but I just can’t get access – I must have messed something up somewhere.
Advertisement
Answer
In my haste, I was trying to run commands before mysql was ready. It can take 90 seconds after a rebuild for the container to accept connections.
docker logs db
Once it was ready to connect, my commands would run.