Docker mysql cant connect to container

2020-02-09 04:23发布

问题:

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.

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

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

回答1:

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.

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.

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"