从容器内部,主机名转换为localhost



这里的目标是我想将这个后端(python(服务器连接到mysql,但问题是"mysql";docker容器中的hostname转换为127.0.0.1,这是错误的,它应该是来自网络的ip,如192.168.x.x。我试图向docker compose文件添加链接和external_links,但没有帮助。我在这里做错了什么?

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: {}

您的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

最新更新