問題描述
我有用于創建 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無法連接到容器的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!