沃梦达 / 编程问答 / php问题 / 正文

Docker mysql无法连接到容器

Docker mysql cant connect to container(Docker mysql无法连接到容器)

本文介绍了Docker mysql无法连接到容器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有用于创建 mysql 映像的 docker-compose 文件并将端口暴露给 3306,但是当我尝试安装 CMS 时,它给我错误,提示它无法连接到数据库.我尝试扫描端口 3306,它显示它已打开,因此 mysql 正在运行.

I've got docker-compose file for creating mysql image and expose port to 3306, but when I try to install CMS, it gives me error that it can't connect to Database. I try to scan port 3306 and it's showing me that it's open so mysql is running.

为什么两个docker容器看不到对方?

Why the two of docker containers can't see each other ?

这是我的 docker-compose 文件:

Here is my docker-compose file:

phpfpm:
  restart: always
  extends:
    file: php-fpm-5.6.yml
    service: phpfpm
  links:
    - db:db

nginx:
  restart: always
  image: nginx
  ports:
    - "8000:80"
  links:
    - phpfpm:phpfpm
  volumes:
    - ./nginx/vhost.conf:/etc/nginx/conf.d/default.conf
    - ./app:/var/www/html
    - ./log/nginx:/var/log/nginx

db:
  restart: always
  image: mysql
  ports:
    - "3306:3306"
  environment:
    MYSQL_ROOT_PASSWORD: 123456
    MYSQL_USER: user
    MYSQL_PASSWORD: password
    MYSQL_DATABASE: database

推荐答案

要连接到数据库,请使用您提供的链接/别名作为主机名.因此,您的 CMS 可以使用 db 作为主机名和端口 3306 连接到 MySQL.

To connect to the database, use the link/alias you provided as a hostname. So, you CMS can connect to MySQL using db as hostname, and port 3306.

您将无法连接到 localhost 或 127.0.0.1,因为localhost"是每个容器内的本地主机,因此,在 phpfpm 容器中使用localhost"将尝试连接到 phpfpm 容器内的 MySQL 数据库,但没有服务器在那里运行.

You won't be able to connect to localhost or 127.0.0.1, because "localhost" is the localhost inside each container, so, using "localhost" in the phpfpm container will try to connect to a MySQL database inside the phpfpm container, but there's no server running there.

请注意,如果您仅从链接的容器内部连接到数据库,则不必发布("3306":"3306")MySQL 端口.发布端口将 MySQL 暴露在公共网络接口上,可能是互联网"

Note that you don't have to publish ("3306":"3306") the MySQL ports if you only connect to the database from inside the linked containers. Publishing the ports exposes MySQL on the public network interface, which may be "the Internet"

这篇关于Docker mysql无法连接到容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Docker mysql无法连接到容器

基础教程推荐