Docker Compose - 无法从单独的Nginx容器连接到MySQL

时间:2017-08-01 18:02:40

标签: docker docker-compose boot2docker

我正在努力使用以下docker设置..一切都运行得很好但是由于某种原因我的nginx容器无法连接到mysql,我已经关注了无数的教程而且没有一个适用于我所以任何建议都会很棒..我的码头组成如下(fpm和nginx工作完美)..

# web server
nginx:
  image: nginx:latest
  ports:
    - "80:80"
    - "443:443" 
  volumes:
    # app
    - ./app/src:/usr/share/nginx/html
    # nginx configs
    - ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro
    - ./nginx/conf.d/:/etc/nginx/conf.d/:ro
    - ./nginx/snippets/:/etc/nginx/snippets/:ro    
    # certificates
    - ./nginx/letsencrypt/fullchain.pem:/etc/letsencrypt/live/example.com/fullchain.pem:ro
    - ./nginx/letsencrypt/privkey.pem:/etc/letsencrypt/live/example.com/privkey.pem:ro
    # logs    
    # - ./logs/nginx-error.log:/var/log/nginx/error.log
    # - ./logs/nginx-access.log:/var/log/nginx/access.log    
  links:
    - fpm:__DOCKER_PHP_FPM__
    - db
# php-fpm
fpm:
  build: ./php-fpm
  ports:
    - "9000"
  volumes:
    - ./app/src:/usr/share/nginx/html
    - ./php-fpm/php-production.ini:/usr/local/etc/php/php.ini:ro
db:
  image: mysql
  environment:
    MYSQL_ROOT_PASSWORD: "admin"
  ports:
    - "3306:3306"      

当我运行docker-compose up时,mysql splurts out了几行有趣的行

    db_1     | 2017-08-01T17:53:15.872664Z 0 [Note] Server hostname (bind-address): '*'; port: 3306
    db_1     | 2017-08-01T17:53:15.872716Z 0 [Note] IPv6 is available.
    db_1     | 2017-08-01T17:53:15.872723Z 0 [Note]   - '::' resolves to '::';
    db_1     | 2017-08-01T17:53:15.872736Z 0 [Note] Server socket created on IP: '::'.
    db_1     | 2017-08-01T17:53:15.911242Z 0 [Note] mysqld: ready for connections.
    db_1     | Version: '5.7.19'  socket: '/var/run/mysqld/mysqld.sock'  port: 3306  MySQL Community Server (GPL)

看起来它不接受TCP连接,并且在我的wp-config.php数据库文件中使用套接字地址也不起作用。

这基本上是wordpress安装屏幕上的内容:

 Warning: mysqli_real_connect(): (HY000/2002): Connection refused in /usr/share/nginx/html/wp-includes/wp-db.php on line 1538

有趣的是,我可以从SequelPro或MySQL工作台连接到数据库没有问题。我对docker(和docker compose)非常新,所以也许我在这里缺少一些东西或一步?

如果重要的话,我在osx上运行docker。

docker ps输出:

    CONTAINER ID        IMAGE                  COMMAND                  CREATED             STATUS              PORTS                                      NAMES
    060ac535e91e        nginx:latest           "nginx -g 'daemon ..."   9 minutes ago       Up 9 minutes        0.0.0.0:80->80/tcp, 0.0.0.0:443->443/tcp   dockerlnmpmaster_nginx_1
    56db5e7bf9c1        mysql                  "docker-entrypoint..."   10 minutes ago      Up 9 minutes        0.0.0.0:3306->3306/tcp                     dockerlnmpmaster_db_1
    6b8d6e4bec5f        dockerlnmpmaster_fpm   "php-fpm"                10 minutes ago      Up 9 minutes        0.0.0.0:32813->9000/tcp                    dockerlnmpmaster_fpm_1

1 个答案:

答案 0 :(得分:1)

最有可能的问题是,当您在主机上而不是在docker容器内测试MySQL访问时。所以,如果你使用localhost:3306连接。有用。这是因为对于db服务,端口映射为3306:3306

但是这个服务不是你的compose容器中的localhost。它由服务名称引用。在您的情况下,db。因此,当您配置wordpress时,您需要确保使用db作为数据库名称