在Django Rest Framework中运行docker-compose up时出现异常
问题描述
在Django Rest Framework中配置安全WebSocket时,我在docker-compose.yml中添加了如下Daphne服务配置:
daphne: platform: linux/amd64 build: context: . dockerfile: Dockerfile.dev command: 'sh -c "daphne -b 0.0.0.0 -p 8000 apps.asgi:application"' restart: always
执行docker-compose up时出现如下错误,移除Daphne条目后错误消失,且此前该compose项目能正常构建运行:
daphne_1 | Traceback (most recent call last): daphne_1 | File "/usr/local/lib/python3.8/site-packages/urllib3/connectionpool.py", line 703, in urlopen daphne_1 | httplib_response = self._make_request( daphne_1 | File "/usr/local/lib/python3.8/site-packages/urllib3/connectionpool.py", line 398, in _make_request daphne_1 | conn.request(method, url, **httplib_request_kw) daphne_1 | File "/usr/local/lib/python3.8/http/client.py", line 1256, in request daphne_1 | self._send_request(method, url, body, headers, encode_chunked) daphne_1 | File "/usr/local/lib/python3.8/http/client.py", line 1302, in _send_request daphne_1 | self.endheaders(body, encode_chunked=encode_chunked) daphne_1 | File "/usr/local/lib/python3.8/http/client.py", line 1251, in endheaders daphne_1 | self._send_output(message_body, encode_chunked=encode_chunked) daphne_1 | File "/usr/local/lib/python3.8/http/client.py", line 1011, in _send_output daphne_1 | self.send(msg) daphne_1 | File "/usr/local/lib/python3.8/http/client.py", line 951, in send daphne_1 | self.connect() daphne_1 | File "/usr/local/lib/python3.8/site-packages/docker/transport/unixconn.py", line 30, in connect daphne_1 | sock.connect(self.unix_socket) daphne_1 | FileNotFoundError: [Errno 2] No such file or directory daphne_1 | daphne_1 | During handling of the above exception, another exception occurred: daphne_1 | daphne_1 | Traceback (most recent call last): daphne_1 | File "/usr/local/lib/python3.8/site-packages/requests/adapters.py", line 440, in send daphne_1 | resp = conn.urlopen( daphne_1 | File "/usr/local/lib/python3.8/site-packages/urllib3/connectionpool.py", line 785, in urlopen daphne_1 | retries = retries.increment( daphne_1 | File "/usr/local/lib/python3.8/site-packages/urllib3/util/retry.py", line 550, in increment daphne_1 | raise six.reraise(type(error), error, _stacktrace) daphne_1 | File "/usr/local/lib/python3.8/site-packages/urllib3/packages/six.py", line 769, in reraise daphne_1 | raise value.with_traceback(tb) daphne_1 | File "/usr/local/lib/python3.8/site-packages/urllib3/connectionpool.py", line 703, in urlopen daphne_1 | httplib_response = self._make_request( daphne_1 | File "/usr/local/lib/python3.8/site-packages/urllib3/connectionpool.py", line 398, in _make_request daphne_1 | conn.request(method, url, **httplib_request_kw) daphne_1 | File "/usr/local/lib/python3.8/http/client.py", line 1256, in request daphne_1 | self._send_request(method, url, body, headers, encode_chunked) daphne_1 | File "/usr/local/lib/python3.8/http/client.py", line 1302, in _send_request daphne_1 | self.endheaders(body, encode_chunked=encode_chunked) daphne_1 | File "/usr/local/lib/python3.8/http/client.py", line 1251, in endheaders daphne_1 | self._send_output(message_body, encode_chunked=encode_chunked) daphne_1 | File "/usr/local/lib/python3.8/http/client.py", line 1011, in _send_output daphne_1 | self.send(msg) daphne_1 | File "/usr/local/lib/python3.8/http/client.py", line 951, in send daphne_1 | self.connect() daphne_1 | File "/usr/local/lib/python3.8/site-packages/docker/transport/unixconn.py", line 30, in connect daphne_1 | sock.connect(self.unix_socket) daphne_1 | urllib3.exceptions.ProtocolError: ('Connection aborted.', FileNotFoundError(2, 'No such file or directory')) daphne_1 | daphne_1 | During handling of the above exception, another exception occurred: daphne_1 | daphne_1 | Traceback (most recent call last): daphne_1 | File "/usr/local/lib/python3.8/site-packages/docker/api/client.py", line 214, in _retrieve_server_version daphne_1 | return self.version(api_version=False)["ApiVersion"] daphne_1 | File "/usr/local/lib/python3.8/site-packages/docker/api/daemon.py", line 181, in version daphne_1 | return self._result(self._get(url), json=True) daphne_1 | File "/usr/local/lib/python3.8/site-packages/docker/utils/decorators.py", line 46, in inner daphne_1 | return f(self, *args, **kwargs) daphne_1 | File "/usr/local/lib/python3.8/site-packages/docker/api/client.py", line 237, in _get daphne_1 | return self.get(url, **self._set_request_timeout(kwargs)) daphne_1 | File "/usr/local/lib/python3.8/site-packages/requests/sessions.py", line 542, in get daphne_1 | return self.request('GET', url, **kwargs) daphne_1 | File "/usr/local/lib/python3.8/site-packages/requests/sessions.py", line 529, in request daphne_1 | resp = self.send(prep, **send_kwargs) daphne_1 | File "/usr/local/lib/python3.8/site-packages/requests/sessions.py", line 645, in send daphne_1 | r = adapter.send(request, **kwargs) daphne_1 | File "/usr/local/lib/python3.8/site-packages/requests/adapters.py", line 501, in send daphne_1 | raise ConnectionError(err, request=request) daphne_1 | requests.exceptions.ConnectionError: ('Connection aborted.', FileNotFoundError(2, 'No such file or directory')) daphne_1 | daphne_1 | During handling of the above exception, another exception occurred: daphne_1 | daphne_1 | Traceback (most recent call last): daphne_1 | File "/usr/local/bin/daphne", line 8, in <module> daphne_1 | sys.exit(CommandLineInterface.entrypoint()) daphne_1 | File "/usr/local/lib/python3.8/site-packages/daphne/cli.py", line 170, in entrypoint daphne_1 | cls().run(sys.argv[1:]) daphne_1 | File "/usr/local/lib/python3.8/site-packages/daphne/cli.py", line 232, in run daphne_1 | application = import_by_path(args.application) daphne_1 | File "/usr/local/lib/python3.8/site-packages/daphne/utils.py", line 12, in import_by_path daphne_1 | target = importlib.import_module(module_path) daphne_1 | File "/usr/local/lib/python3.8/importlib/__init__.py", line 127, in import_module daphne_1 | return _bootstrap._gcd_import(name[level:], package, level) daphne_1 | File "<frozen importlib._bootstrap>", line 1014, in _gcd_import daphne_1 | File "<frozen importlib._bootstrap>", line 991, in _find_and_load daphne_1 | File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked daphne_1 | File "<frozen importlib._bootstrap>", line 671, in _load_unlocked daphne_1 | File "<frozen importlib._bootstrap_external>", line 843, in exec_module daphne_1 | File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed daphne_1 | File "/app/./apps/asgi.py", line 14, in <module> daphne_1 | django_asgi_app = get_asgi_application() daphne_1 | File "/usr/local/lib/python3.8/site-packages/django/core/asgi.py", line 12, in get_asgi_application daphne_1 | django.setup(set_prefix=False) daphne_1 | File "/usr/local/lib/python3.8/site-packages/django/__init__.py", line 24, in setup daphne_1 | apps.populate(settings.INSTALLED_APPS) daphne_1 | File "/usr/local/lib/python3.8/site-packages/django/apps/registry.py", line 122, in populate daphne_1 | app_config.ready() daphne_1 | File "/app/./apps/environments/apps.py", line 8, in ready daphne_1 | from . import signals daphne_1 | File "/app/./apps/environments/signals.py", line 6, in <module> daphne_1 | from apps.cloud.tasks import remove_periodic_tasks daphne_1 | File "/app/./apps/cloud/tasks.py", line 21, in <module> daphne_1 | from apps.cloud.utils import ( daphne_1 | File "/app/./apps/cloud/utils.py", line 10, in <module> daphne_1 | client: DockerClient = docker.from_env() daphne_1 | File "/usr/local/lib/python3.8/site-packages/docker/client.py", line 96, in from_env daphne_1 | return cls( daphne_1 | File "/usr/local/lib/python3.8/site-packages/docker/client.py", line 45, in __init__ daphne_1 | self.api = APIClient(*args, **kwargs) daphne_1 | File "/usr/local/lib/python3.8/site-packages/docker/api/client.py", line 197, in __init__ daphne_1 | self._version = self._retrieve_server_version() daphne_1 | File "/usr/local/lib/python3.8/site-packages/docker/api/client.py", line 221, in _retrieve_server_version daphne_1 | raise DockerException( daphne_1 | docker.errors.DockerException: Error while fetching server API version: ('Connection aborted.', FileNotFoundError(2, 'No such file or directory'))
解决方案
从错误栈可以定位到:Daphne启动时,Django初始化过程中加载了apps/cloud/utils.py里的docker.from_env()调用——这个调用试图连接宿主机的Docker守护进程,但默认容器内没有挂载Docker套接字,导致找不到套接文件报错。
提供两种解决思路:
思路一:挂载Docker套接字到容器
修改docker-compose.yml的Daphne服务配置,添加Docker套接字挂载:
daphne: platform: linux/amd64 build: context: . dockerfile: Dockerfile.dev command: 'sh -c "daphne -b 0.0.0.0 -p 8000 apps.asgi:application"' restart: always volumes: - /var/run/docker.sock:/var/run/docker.sock # 挂载宿主机Docker套接字
注意:如果容器内运行Daphne的用户没有读写Docker套接字的权限,需要确保该用户属于docker组,或者调整套接字权限(生产环境优先用组权限方式)。
思路二:延迟Docker客户端初始化
如果应用不需要在Django启动阶段就初始化Docker客户端,可以把docker.from_env()的调用延迟到实际使用时(比如任务函数内部),避免启动阶段触发连接。
修改apps/cloud/utils.py:
# 原代码 client: DockerClient = docker.from_env() # 修改后 def get_docker_client(): return docker.from_env() # 在需要使用的地方调用 # client = get_docker_client()
内容的提问来源于stack exchange,提问作者Neo
相关产品推荐
相关产品推荐

