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

Docker容器内进程与宿主机Socket连接被拒问题求助

问题原因与解决方案

核心问题

你的Lua服务绑定在localhost(127.0.0.1),这意味着它只接受来自宿主机本地进程的连接;而容器内的Python代码用localhost发起连接时,指向的是容器自身的网络栈,不是宿主机,所以会出现连接拒绝。

步骤1:修改Lua服务的绑定地址

把Lua服务的绑定地址从localhost改为0.0.0.0,让它能接收来自所有网络接口的连接:

local socket = require("socket")
local host = "0.0.0.0"  -- 替换原localhost
local port = 1234
local server = assert(socket.bind(host, port))
server:settimeout(0)

local function sendData(data)
    local client = server:accept()
    if client then
        client:send(data .. "\n")
        client:close()
    end
end

步骤2:修改容器内Python的目标地址

容器内不能用localhost访问宿主机,需要替换为宿主机在Docker网络中的地址:

  • Docker Desktop(Windows/macOS/Linux):直接使用host.docker.internal,这是Docker提供的默认别名,指向宿主机
  • 手动指定IP:如果上述别名无效,可通过docker inspect bridge查看网桥的Gateway字段(通常Linux上是172.17.0.1),用该IP作为host

修改后的Python代码:

import socket

host = "host.docker.internal"  # 或手动获取的宿主机Docker网桥IP
port = 1234
def receive_data():
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.connect((host, port))
        data = s.recv(1024).decode()
        if data:
            return data.split(',')

额外检查

  • 确保宿主机防火墙没有拦截1234端口的入站连接
  • 确认Docker端口映射-p 127.0.0.1:1234:1234正常(你当前的命令已经配置,无需修改)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 04:16:03