无法使用IP访问Docker数据库(仅限localhost)

时间:2017-11-14 15:12:39

标签: docker networking localhost

我正在尝试设置Docker以允许来自网络上其他设备的连接。目前要访问Docker,请访问我的计算机上的localhost。我正在尝试使用计算机的本地IP(192.168.0.140)进行连接,这样可以让我看到我的文件但不能连接到我的数据库。

我认为这是我的配置问题,但我不太了解Docker对其进行故障排除。

version: '2'

services:
  webserver:
    build: ./docker/webserver
    image: localdev
    ports:
      - '80:80'
      - '443:443'
    volumes:
      - ./www:/var/www/html
    links:
      - db

  db:
    image: mysql:5.6
    ports:
      - 3306
    volumes:
      - ./db:/var/lib/mysql
    environment:
      - MYSQL_ROOT_PASSWORD=secret

  phpmyadmin:
    image: phpmyadmin/phpmyadmin:latest
    links:
      - db
    environment:
      PMA_HOST: db
      PMA_PORT: 3306
      MYSQL_USER: root
      MYSQL_ROOT_PASSWORD: secret
    ports:
      - '8080:80'

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

您能够连接到其他容器的原因是您已映射容器和主机之间的端口。 对于数据库,您使用的是短端口语法:

ports:
  - 3306

这将在主机上选择一个随机端口。要能够连接到数据库,请使用长格式语法:

ports:
  - '3306:3306'

在这种情况下,您将能够在localhost:3306

上连接到数据库

答案 1 :(得分:0)

也许你应该这样试试:

version: '2'

services:
  webserver:
    build: ./docker/webserver
    image: localdev
    ports:
      - '0.0.0.0:80:80'   # Map container port 80 on your "public" ip on port 80, it will be available on the network 
      - '0.0.0.0:443:443' # Same for port 443 
    volumes:
      - ./www:/var/www/html
    links:
      - db

  db:
    image: mysql:5.6
    # ports:
    #  - 3306    # You don't need to map port 3306 because mysql already expose this port for others containers, unless you wan't to access to your mysql directly
    volumes:
      - ./db:/var/lib/mysql
    environment:
      - MYSQL_ROOT_PASSWORD=secret

  phpmyadmin:
    image: phpmyadmin/phpmyadmin:latest
    #links:
    #  - db # Not necessary, with docker-compose v2 every containers are in the same network and see each other
    environment:
      PMA_HOST: db
      PMA_PORT: 3306
      MYSQL_USER: root
      MYSQL_ROOT_PASS
      WORD: secret
    ports:
      - 'localhost:8080:80' # to keep your phpmyadmin only available from localhost.