我有用于创建mysql映像的docker-compose文件并将端口暴露给3306,但是当我尝试安装CMS时,它给出了错误,它无法连接到数据库.我尝试扫描端口3306,它显示它是打开的,所以mysql正在运行.
为什么两个docker容器看不到对方?
这是我的docker-compose文件:
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.
您将无法连接到localhost或127.0.0.1,因为“localhost”是每个容器内的localhost,因此,在phpfpm容器中使用“localhost”将尝试连接到phpfpm容器内的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”