【问题标题】:From inside container, the hostname translates to localhost从容器内部,主机名转换为 localhost
【发布时间】:2021-12-21 13:18:40
【问题描述】:

这里的目标是我想将此后端(python)服务器连接到 mysql,但问题是 docker 容器内的“mysql”主机名转换为 127.0.0.1 这是错误的,它应该是来自的 ip像 192.168.x.x 这样的网络。我尝试将链接和 external_links 添加到 docker compose 文件中,但没有帮助。 我在这里做错了什么?

version: "3.0"

services:
  client:
    build: frontend
    image: project/client
    ports:
      - "8090:80"
    networks:
      - frontend

  server:
    build: ./server
    image: project/server
    networks:
      - backend
      - frontend
    depends_on:
      - mysql
    volumes:
      - project-server-vol:/data
    ports:
      - "8080:8080"

  mysql:
    image: mysql:latest
    networks:
      - backend
    environment:
      - MYSQL_ROOT_PASSWORD=my-secret-pw
    volumes:
      - project-mysql-vol:/var/lib/mysql
    ports:
      - "3306:3306"

volumes:
 project-server-vol: {}
 project-mysql-vol: {}

networks:
  frontend: {}
  backend: {}

【问题讨论】:

  • 在哪个容器内解析为127.0.0.1?
  • 请包括您如何验证 mysql DNS 解析错误的输出。像 nicolaka/netshoot 这样的项目可能会有所帮助。
  • @HansKilian 我正在尝试从服务器容器中解析。
  • 能否请您提供两个网络的docker network inspect name(用docker network ls 查找名称)?
  • 当我尝试复制它时,mysql 从服务器容器内解析为 192.168.144.2

标签: docker docker-compose


【解决方案1】:

您的 mysql 不应该解析为 127.0.0.1,请确保您的主机的 /etc/hosts 文件没有任何类似 127.0.0.1 mysql 的条目。试试下面的 docker-compose.yaml:

version: '3.8'
networks:
  frontend:
  backend:
services:
  nginx1:
    image: nginx:alpine
    networks:
    - frontend
  nginx2:
    image: nginx:alpine
    networks:
    - frontend
    - backend
  nginx3:
    image: nginx:alpine
    networks:
    - backend

docker-compose up -d
docker-compose exec nginx1 wget -qO- nginx2 #-- OK, notice you access using service name "nginx2"
docker-compose exec nginx2 wget -qO- nginx3 #-- OK, notice you access using service name "nginx3"
docker-compose exec nginx1 wget -qO- nginx3 #-- expected to fail as not on the same network.
docker-compose down

上面的示例被证明是有效的。如果你的机器上一切顺利,你可以用你的前端替换 nginx1,用你的服务器替换 nginx2,用你的 mysql 替换 nginx3。它应该证明你的mysql不应该解析为127.0.0.1

【讨论】:

    猜你喜欢
    • 2020-02-28
    • 2021-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-25
    • 1970-01-01
    • 1970-01-01
    • 2018-07-18
    相关资源
    最近更新 更多