Docker Compose容器访问主机TCP服务器问题求助
问题:Docker容器内Spark集群无法连接Windows本地TCP服务器
我正在学习Docker,对容器端口访问与暴露有疑问。用自定义Docker Compose部署的Spark集群运行正常,但Windows 10本地运行的TCP服务器(每隔0.5秒发送单词),Spark Master容器无法连接它来处理文本。
相关配置与代码
Docker Compose文件
version: "3.7" services: spark-master: build: context: ./spark dockerfile: ./Dockerfile container_name: "spark-master" environment: - SPARK_MODE=master - SPARK_LOCAL_IP=spark-master - SPARK_RPC_AUTHENTICATION_ENABLED=no - SPARK_RPC_ENCRYPTION_ENABLED=no - SPARK_LOCAL_STORAGE_ENCRYPTION_ENABLED=no - SPARK_SSL_ENABLED=no ports: - "7077:7077" - "8080:8080" volumes: - ./src:/src - ./data:/data - ./output:/output spark-worker-1: image: docker.io/bitnami/spark:3.1 container_name: "spark-worker-1" environment: - SPARK_MODE=worker - SPARK_MASTER_URL=spark://spark-master:7077 - SPARK_WORKER_MEMORY=2G - SPARK_WORKER_CORES=1 - SPARK_RPC_AUTHENTICATION_ENABLED=no - SPARK_RPC_ENCRYPTION_ENABLED=no - SPARK_LOCAL_STORAGE_ENCRYPTION_ENABLED=no - SPARK_SSL_ENABLED=no spark-worker-2: image: docker.io/bitnami/spark:3.1 container_name: "spark-worker-2" environment: - SPARK_MODE=worker - SPARK_MASTER_URL=spark://spark-master:7077 - SPARK_WORKER_MEMORY=2G - SPARK_WORKER_CORES=1 - SPARK_RPC_AUTHENTICATION_ENABLED=no - SPARK_RPC_ENCRYPTION_ENABLED=no - SPARK_LOCAL_STORAGE_ENCRYPTION_ENABLED=no - SPARK_SSL_ENABLED=no
Windows本地TCP服务器脚本
import socket import time host = 'localhost' port = 9999 servidor = socket.socket(socket.AF_INET, socket.SOCK_STREAM) servidor.bind((host, port)) servidor.listen() print(f"Server TCP/IP: {host}:{port}...") while True: conexion, direccion = servidor.accept() print(f"conexion: {direccion[0]}:{direccion[1]}") while True: palabra = "HELLO" conexion.sendall(palabra.encode()) time.sleep(0.5)
Spark Master容器内脚本
from pyspark import SparkContext,SparkConf from pyspark.streaming import StreamingContext if __name__ == "__main__": sc = SparkContext(appName= "miDstream") sc.setLogLevel("ERROR") ssc= StreamingContext(sc, 10) inputStream= ssc.socketTextStream("localhost",9999) nuevoDStream = inputStream.map(lambda record: record.upper()) nuevoDStream.pprint() ssc.start() ssc.awaitTermination()
解决方案
核心问题
容器内的localhost指向容器自身,而非Windows宿主机,所以Spark脚本用localhost无法访问到本地TCP服务器。
修复步骤
1. 调整TCP服务器绑定地址
把Windows本地TCP服务器的绑定地址从localhost改为0.0.0.0,允许所有网卡接入:
# 替换原host变量 host = '0.0.0.0'
2. 修改Spark脚本的连接地址
Windows Docker环境中,容器访问宿主机需要用特殊地址host.docker.internal,替换Spark脚本中的localhost:
# 替换原socketTextStream的地址 inputStream= ssc.socketTextStream("host.docker.internal",9999)
3. 可选:验证端口连通性
在Spark Master容器内执行以下命令,测试是否能连通Windows本地9999端口:
telnet host.docker.internal 9999 # 若容器有nc工具,也可使用 nc -zv host.docker.internal 9999
4. 重启服务
- 重启Windows本地的TCP服务器脚本
- 重新运行Spark容器内的Streaming脚本
调整后,Spark Master容器即可正常连接Windows本地TCP服务器,接收流式数据。
内容的提问来源于stack exchange,提问作者yaviens
相关产品推荐
相关产品推荐

