45 lines
3.1 KiB
Markdown
45 lines
3.1 KiB
Markdown
---
|
||
title: "WSL2 中 Docker 容器访问宿主机代理"
|
||
type: source
|
||
tags: [wsl, docker, proxy]
|
||
date: 2026-05-02
|
||
---
|
||
|
||
## Source File
|
||
- [[Home Office/WSL2 中 Docker 容器访问宿主机代理]]
|
||
|
||
## Summary(用中文描述)
|
||
- 核心主题:WSL2 环境下 Docker 容器如何正确访问宿主机(Windows)上运行的代理服务
|
||
- 问题域:WSL2 网络隔离场景下的容器代理配置
|
||
- 方法/机制:使用 Docker 内置 DNS 名称 `host.docker.internal` 替代 `127.0.0.1`/`localhost`,Docker Desktop/WSL2 环境自动解析为宿主机 IP
|
||
- 结论/价值:避免容器内 localhost 指向自身导致的代理访问失败;适用于 pip/apt-get/curl 等各种命令的代理配置
|
||
|
||
## Key Claims(用中文描述)
|
||
- **WSL2 Docker 容器 + 宿主机代理**:在 WSL2 环境下运行的 Docker 容器,必须使用 `host.docker.internal` 而非 `127.0.0.1` 访问宿主机代理,因为容器内的 `127.0.0.1` 指向容器自身而非宿主机
|
||
- **pip 代理配置**:Dockerfile 中 `pip install --proxy http://host.docker.internal:10808` 可正确走宿主机代理
|
||
- **apt 代理配置**:`apt-get -o Acquire::http::Proxy="http://host.docker.internal:10808" update` 可正确走宿主机代理
|
||
- **curl 代理配置**:`curl -x http://host.docker.internal:10808 <url>` 可正确走宿主机代理
|
||
- **Clash 代理前提**:代理软件(如 Clash)必须开启「允许局域网连接」选项
|
||
|
||
## Key Quotes
|
||
> "容器内的 `127.0.0.1` 指向容器自身,无法访问宿主机代理。需用 Docker 内置 DNS 名称替代。" — 核心问题说明
|
||
> "避免在 Dockerfile 中硬编码 `ENV HTTPS_PROXY=http://127.0.0.1:...`,容器内无法访问" — Dockerfile 最佳实践
|
||
|
||
## Key Concepts
|
||
- [[DockerHostNetworking]]:`host.docker.internal` 是 Docker 提供的特殊 DNS 名称,用于容器访问宿主机网络,属于 DockerHostNetworking 概念的 Linux/WSL2 实现方式
|
||
|
||
## Key Entities
|
||
- [[WSL2]]:Windows Subsystem for Linux 2,本文档的技术背景平台;WSL2 默认 NAT 网络模式下容器内 `127.0.0.1` 指向自身
|
||
- [[Clash]]:本文档示例中宿主机上运行的代理软件,需开启「允许局域网连接」才能被容器访问
|
||
|
||
## Connections
|
||
- [[DockerHostNetworking]] ← documented_in ← [[WSL2-中-Docker-容器访问宿主机代理]](本文档记录了 `host.docker.internal` 在 WSL2 Docker 场景下的具体用法)
|
||
- [[WSL2-中-Docker-容器访问宿主机代理]] ← extends ← [[WSL2 启动与网络配置指南]](本文档补充了 WSL2 Docker 容器访问宿主机代理这一具体场景)
|
||
|
||
## Contradictions
|
||
- 与 [[n8n-docker-配置-telegram-代理-troubleshooting]] 细节差异:
|
||
- 冲突点:`host.docker.internal` 的可用性前提
|
||
- 当前观点(n8n 文档):需要 `extra_hosts: - "host.docker.internal:host-gateway"` 配置才能使用
|
||
- 对方观点(本文档):Docker Desktop(Windows/Mac)及 WSL2 环境下均可用,未提及 `extra_hosts`
|
||
- 说明:两者可能均正确,差异在于 Docker Desktop for Windows 内置支持 vs 纯 WSL2(无 Docker Desktop)的不同配置要求
|