Laravel无法连接到dockerise数据库

时间:2017-07-25 10:25:24

标签: php mysql nginx docker ansible

我创建了三个容器(PhP-NGINX-MySql)来支持位于主机上的默认laravel项目。

当我尝试从laravel连接到DB时,我收到错误:

Route::get('/', function () {
    dd(App\User::all());
    return view('welcome');
});
  

SQLSTATE [HY000] [2002] php_network_getaddresses:getaddrinfo失败:   名称或服务未知(SQL:select * from users

这是laravel-5.3.16中的.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=33061
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret

和ansible-playbook:

---
- hosts: localhost
  environment:
    PYTHONPATH: /usr/local/lib/python2.7/site-packages/

  tasks:

  - name: get currernt location
    command: pwd
    register: my_way

  - set_fact: host_dir="{{my_way.stdout}}"

  - name: create image with nginx
    docker_image:
      path: /home/demaunt/Jun/dock_click/engie
      dockerfile: engie.dockerfile
      name: engie_image

  - name: create image with php
    docker_image:
      path: /home/demaunt/Jun/dock_click/piha
      dockerfile: piha.dockerfile
      name: piha_image

  - name: run piha container
    docker_container:
      name: piha_cont
      image: piha_image
      volumes:
        - "/home/demaunt/Dockjun/laravel-5.3.16:/var/www/wapclick"
      links:
        - diba_cont:db
      env:
        DB_PORT: 3306
        DB_HOST: database

  - name: run engie container
    docker_container:
      name: engie_cont
      image: engie_image
      volumes_from:
        - piha_cont
      ports:
        - "8080:80"
      links:
        - piha_cont:app  

  - name: run diba container
    docker_container:
      name: diba_cont
      image: mysql:5.6
      env:
        MYSQL_DATABASE: homestead
        MYSQL_USER: homestead
        MYSQL_PASSWORD: secret
        MYSQL_ROOT_PASSWORD: secret 
      ports:
       - 33061:3306

更奇怪的是,当我运行 php artisan migrate 时,我获得了成功的消息:

Migration table created successfully.
Migrated: 2014_10_12_000000_create_users_table
Migrated: 2014_10_12_100000_create_password_resets_table

以下是运行的容器:

docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                           NAMES
e926382db347        engie_image         "nginx -g 'daemon ..."   19 seconds ago      Up 18 seconds       443/tcp, 0.0.0.0:8080->80/tcp   engie_cont
c9563c839e45        piha_image          "docker-php-entryp..."   19 seconds ago      Up 18 seconds       9000/tcp                        piha_cont
5de541049da2        mysql:5.6           "docker-entrypoint..."   20 seconds ago      Up 19 seconds       0.0.0.0:33061->3306/tcp         diba_cont

1 个答案:

答案 0 :(得分:1)

尝试" diba_cont"作为DB_HOST应该做的工作。 Docker自动声明一个DNS规则,其中包含要与容器联系的容器名称