我想使用php 7.2.10-fpm,nginx和mysql 5.7设置一个小型docker环境,以便在其中运行Laravel 5.7。不幸的是,当尝试从我的应用程序服务连接到mysql(尝试运行docker-composer exec app php artisan migrate
)时,出现以下错误:
In Connector.php
SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known
PDO::__construct(): php_network_getaddresses: getaddrinfo failed: Name or service not known
尝试运行docker-compose exec app mysql -u root -p
会返回:
错误2002(HY000):无法通过套接字'/var/run/mysqld/mysqld.sock'(2“无此文件或目录”)连接到本地MySQL服务器
通过docker-compose up --build
启动和构建容器不会引发任何错误。它表示mysql正在运行并正在等待连接。
我还通过docker system prune --force --volumes
删除并重新创建了所有图像。
也许我错过了docker-compose.yml中的某些内容?
version: '3.3'
services:
app:
build:
context: ./
dockerfile: app.dockerfile
working_dir: /var/www
volumes:
- ./../backend:/var/www
environment:
- "DB_PORT=3306"
- "DB_HOST=database"
web:
build:
context: ./
dockerfile: web.dockerfile
working_dir: /var/www
depends_on:
- mysql
volumes:
- ./../backend:/var/www
ports:
- 8080:80
mysql:
image: mysql:5.7
volumes:
- db_data:/var/lib/mysql
restart: always
environment:
- "MYSQL_DATABASE=shop"
- "MYSQL_USER=shop_u"
- "MYSQL_PASSWORD=secret"
- "MYSQL_ROOT_PASSWORD=secret"
ports:
- 33061:3306
command: --disable-partition-engine-check
volumes:
db_data:
App.dockerfile:
FROM php:7.2.10-fpm
RUN apt-get update
RUN apt-get install -y libmcrypt-dev
RUN apt-get install -y mysql-client
RUN apt-get install -y libmagickwand-dev --no-install-recommends
RUN pecl install imagick
RUN docker-php-ext-enable imagick
RUN docker-php-ext-install pdo_mysql
RUN pecl install mcrypt-1.0.1
RUN docker-php-ext-enable mcrypt
RUN php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
RUN php -r "if (hash_file('SHA384', 'composer-setup.php') === '93b54496392c062774670ac18b134c3b3a95e5a5e5c8f1a9f115f203b75bf9a129d5daa8ba6a13e2cc8a1da0806388a8') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
RUN php composer-setup.php
RUN php -r "unlink('composer-setup.php');"
RUN mv composer.phar /usr/local/bin/composer
RUN apt-get install -y git
RUN apt-get update && apt-get install -y zlib1g-dev
RUN docker-php-ext-install zip
最后是我来自Laravel的.env文件:
DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=3306
DB_DATABASE=shop
DB_USERNAME=shop_u
DB_PASSWORD=secret
docker-compose images
列出了以下容器:
+-----------------+-------------------+----------------+
| Container | Repository | ImageID |
+-----------------+-------------------+----------------+
| docker_app_1 | docker_app | a94dba376130 |
| docker_mysql_1 | docker_database | 563a026a1511 |
| docker_web_1 | docker_web | d9024ab40b73 |
+-----------------+-------------------+----------------+
从ping docker_mysql_1
运行docker exec -it docker_app_1 bash
会产生bash: ping: command not found
。
从ping docker_mysql_1
运行docker exec -it docker_web_1 bash
很好。