[英]Can connect to database from outside a docker container but not from inside (in laravel)
I refactored this question due to the down votes.由于反对票,我重构了这个问题。
It comes as simple as this:就这么简单:
Outside docker container:外部码头集装箱:
➜ backoffice git:(master) ✗ php artisan tinker
Psy Shell v0.9.9 (PHP 7.2.15 — cli) by Justin Hileman
>>> $ur = app(MDiPaolo\Repositories\UserRepository::class)
=> App\Infrastructure\Repositories\Doctrine\UserDoctrineRepository {#3159}
>>> $u = new MDiPaolo\Entities\User
=> MDiPaolo\Entities\User {#3295}
>>> $u->setEmail('one_email@gmail.com')
=> MDiPaolo\Entities\User {#3295}
>>> $u->setPassword(password_hash('1234', PASSWORD_BCRYPT))
=> null
>>> $ur->save($u)
=> null
>>>
Inside docker container:码头集装箱内部:
➜ backoffice git:(master) ✗ docker exec -it backoffice_web_1 bash
root@042969f0229c:/var/www/html# php artisan tinker
Psy Shell v0.9.9 (PHP 7.2.17 — cli) by Justin Hileman
>>> $ur = app(MDiPaolo\Repositories\UserRepository::class)
Doctrine/DBAL/Exception/ConnectionException with message 'An exception occurred in driver: SQLSTATE[HY000] [2002] Connection refused'
>>>
I have the feeling it is related with the docker system, say the communication between both containers or how i built them.我感觉它与 docker 系统有关,比如两个容器之间的通信或我如何构建它们。
This is my Dockerfile.这是我的 Dockerfile。
FROM php:7.2-apache
RUN docker-php-ext-install pdo_mysql && docker-php-ext-enable pdo_mysql
RUN apt-get update && apt-get install nano && mv "$PHP_INI_DIR/php.ini-development" "$PHP_INI_DIR/php.ini"
RUN a2enmod rewrite
RUN service apache2 restart
ENV APACHE_DOCUMENT_ROOT=/var/www/html/public
RUN sed -ri -e 's!/var/www/html!${APACHE_DOCUMENT_ROOT}!g' /etc/apache2/sites-available/*.conf
RUN sed -ri -e 's!/var/www/!${APACHE_DOCUMENT_ROOT}!g' /etc/apache2/apache2.conf /etc/apache2/conf-available/*.conf
docker-compose file: docker-compose 文件:
version: '3.1'
services:
web:
build: .
ports:
- "8080:80"
links:
- mysql
depends_on:
- mysql
volumes:
- ./:/var/www/html
mysql:
image: mysql:5.7.25
ports:
- "3306:3306"
environment:
MYSQL_ROOT_PASSWORD: backoffice
Ok i found the solution.好的,我找到了解决方案。
IN the .env file the DB_HOST
field has to be equal to the name of mysql container in the docker-compose.yml
file, in my case mysql
.在 .env 文件中,
DB_HOST
字段必须等于docker-compose.yml
文件中 mysql 容器的名称,在我的例子中是mysql
。
DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=3306
DB_DATABASE=dashboard
DB_USERNAME=root
DB_PASSWORD=backoffice
Problem would be that now i cannot access it from the outside, but of course you can always go:问题是现在我无法从外部访问它,但当然你可以随时去:
127.0.0.1 mysql
at your hosts
file在您的
hosts
文件中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.