This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the containerization category.
Last Updated: 2024-11-21
Be careful of different hostnames within the docker world vs. outside. For
example, in a dockerized Laravel app, when I set DB_HOST
in my .env
file to
mysql_docker
(i.e. the container name of my container), it failed to connect
to the DB when -- on my host machine -- I ran:
$ php artisan migrate
However it worked when I ran the same command from within the Docker container:
$ docker-compose exec -u root -T app php artisan migrate --force
In other words, host names based on container names (e.g. mysql_docker
) are
only available when you execute the code within the docker container. This makes
sense and isn't surprising, but can prove confusing when you're in the heat of
the moment and new to containers.
If I wanted the access the DB from outside docker, I should have used localnost IP address
DB_HOST=127.0.0.1
# The correct port must also be set!
Note too that the ports differ on each side. In docker compose I had the mysql
ports as: 8306:3306
. This means 8306 on 127.0.0.1 on my host machine, but 3306
on mysql_docker within any container.