Last Updated: 2024-03-02
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.
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
# The correct port must also be set!
Note too that the ports differ on each side. In docker compose I had the mysql
8306:3306. This means 8306 on 127.0.0.1 on my host machine, but 3306
on mysql_docker within any container.