You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Docker Compose将容器与宿主机网络隔离

容器网络外部访问完全隔离解决方案

核心问题原因

你当前的docker-compose.yml中配置了ports: - 4000:4000/tcp,这会将容器的4000端口绑定到宿主机的所有网络接口(包括localhost),这就是外部能通过localhost:4000访问容器的根本原因。

解决方案步骤

  • 移除端口映射配置:直接删除ports这一项,这是切断外部访问的关键操作。
  • 确认Socket监听地址:保持你的Python脚本监听容器自身的IP(10.1.0.5),不要改成0.0.0.0,确保服务仅在容器所在的自定义bridge网络内响应请求。

修改后的完整docker-compose文件

version: '3.5'

services:
  relayG1_1:
    container_name: relayG1_1
    image: image
    command: python3 server.py 10.1.0.5
    networks:
      first_network:
        ipv4_address: 10.1.0.5

networks:
  first_network:
    name: first_network
    driver: bridge
    ipam:
     config:
       - subnet: 10.1.0.0/24
         gateway: 10.1.0.1

效果说明

修改后,你的容器只会在自定义的first_network桥接网络内部可见和可访问,外部(包括宿主机的localhost)无法直接连接到容器的服务。如果需要其他容器和它通信,只需将那些容器也加入到first_network网络中即可。

内容的提问来源于stack exchange,提问作者bob

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 13:05:25