Docker 服务访问127.0.0.1上的其他服务?
我想让我的web Docker容器从web容器中访问127.0.0.1:6379上的Redis。我已经设置了Docker Compose文件,如下所示。我得到了Docker 服务访问127.0.0.1上的其他服务?,docker,docker-compose,Docker,Docker Compose,我想让我的web Docker容器从web容器中访问127.0.0.1:6379上的Redis。我已经设置了Docker Compose文件,如下所示。我得到了econnrefered尽管: version: "3" services: web: build: . ports: - 8080:8080 command: ["test"] links: - redis:127.0.0.1 redis: image: redi
econnrefered
尽管:
version: "3"
services:
web:
build: .
ports:
- 8080:8080
command: ["test"]
links:
- redis:127.0.0.1
redis:
image: redis:alpine
ports:
- 6379
有什么想法吗?对此的简短回答是“不要”。Docker容器每个都有自己的环回接口127.0.0.1,它与主机环回和其他容器的环回接口分开。你不能重新定义127.0.0.1,如果可以的话,这几乎肯定会破坏其他东西
有一种技术上可行的方法,可以直接在主机上运行所有容器,包括:
network_mode: "host"
但是,这将删除您希望与容器一起使用的docker网络隔离
您还可以通过以下方式将一个容器连接到另一个容器的网络(因此它们具有相同的环回接口):
但我不确定在docker compose
中是否有这样做的语法,而且它在swarm模式下不可用,因为容器可能在不同的节点上运行。我对这种语法的主要用途是附加网络调试工具,如
您应该做的是将redis数据库的位置作为webapp容器的配置参数。将位置作为环境变量、配置文件或命令行参数传入。如果web应用程序无法直接支持此功能,请使用在启动web应用程序之前运行的入口点脚本更新配置。这会将您的compose yml文件更改为:
version: "3"
services:
web:
# you should include an image name
image: your_webapp_image_name
build: .
ports:
- 8080:8080
command: ["test"]
environment:
- REDIS_URL=redis:6379
# no need to link, it's deprecated, use dns and the network docker creates
#links:
# - redis:127.0.0.1
redis:
image: redis:alpine
# no need to publish the port if you don't need external access
#ports:
# - 6379
您用于启动服务的
docker compose
命令是什么?为什么您需要以127.0.0.1:6379
的形式访问它,而不是将其称为redis:6379
?@BMitch web脚本可以a)在开发时使用redis的本地主机实例(例如手动安装在我的笔记本电脑上)b)能够在docker Compose上下文中运行。在web应用程序中,使用127.0.0.1。redis数据库的位置应该是可以传入的配置参数,而不是应用程序中的硬编码。然后,您只需使用配置文件、环境变量或CLI参数传入不同的配置。您还可以在桌面开发中使用docker容器。无需在一个环境中开发并在另一个环境中运行。
version: "3"
services:
web:
# you should include an image name
image: your_webapp_image_name
build: .
ports:
- 8080:8080
command: ["test"]
environment:
- REDIS_URL=redis:6379
# no need to link, it's deprecated, use dns and the network docker creates
#links:
# - redis:127.0.0.1
redis:
image: redis:alpine
# no need to publish the port if you don't need external access
#ports:
# - 6379