我有一个python socket应用程序,在本地运行时工作得很好。但是,当我将它移动到Docker中时,外部客户端无法连接并抛出此错误:
socketio.exceptions.ConnectionError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response'))
WebSocket服务器是真正的基础和发布到0.0.0.0:8080
。我的客户端应用程序监听localhost:8080
。在我的Docker容器中,我暴露了端口8080。我猜我的容器设置不正确。:
Dockerfile:
FROM python:latest
WORKDIR /path/to/project
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
docker-compose.yml
version: "3.9"
services:
app:
build: .
working_dir: /path/to/project
stdin_open: true
tty: true
ports:
- "8080:8080"
volumes:
- type: bind
source: .
target: /path/to/project
我用docker-compose up
启动我的容器,我使用Docker桌面(如果有帮助的话)。我使用这个环境进行开发,所以我用python my_server.py
启动服务器。服务器启动成功。我还错过了什么?
根据网上其他人对这个问题的看法,我尝试了以下方法
- 显式设置
0.0.0.0
为主机 使用 - 设置网络模式为
host
EXPOSE 8080
在我的Dockerfile您的容器连接正常。
您没有指定任何要在容器中运行的命令。为了确保您的服务器实际上在端口8080上运行,您可以在Dockerfile中添加CMD
指令或在docker-compose.yaml
中指定cmd。可以使用以下命令:
CMD ["python", "my_server.py"]
或将docker-compose.yaml
文件设置为:
version: "3.9"
services:
app:
build: .
working_dir: /path/to/project
stdin_open: true
tty: true
command: python my_server.py #<== this overrides the Dockerfile CMD instruction
ports:
- "8080:8080"
volumes:
- type: bind
source: .
target: /path/to/project
您可以在docker-compose.yaml
中了解更多关于command
的信息。
这也是推荐使用docker进行开发的方法。在运行容器中运行命令进行开发工作不是正确的方式。每次测试新更改时,实际上都要运行docker compose。这就避免了很多问题,比如网络无法连接。