跳至主要内容

开发者终端与命令行代理完全指南:curl、git、npm 与 Docker 容器极速加速

专为程序员与 DevOps 工程师编写的命令行代理实战教程,系统详解 Linux / macOS / WSL 终端下 HTTP(S) 与 SOCKS5 环境变量注入、Git SSH 代理配置及 Docker Daemon 镜像拉取加速。

发布日期:
最后更新:
标签: #终端代理 #Git代理 #Docker代理 #开发环境 #网络配置教程

终端为什么“不听使唤”?

在开发过程中,最让人抓狂的情景莫过于:

  • 浏览器打开 github.com 秒开无压力;
  • 但在终端敲下 git clone https://github.com/... 时,光标原地卡死 5 分钟,最后弹出 Fatal: Failed to connect to github.com port 443: Timed out;
  • 执行 npm install、pip install 或 docker pull 时同样报错连连。

根本原因在于:Unix 终端与大多数底层开发工具,为了安全与标准化设计,默认完全忽略桌面图形界面的系统代理设置。


一、终端通用环境变量快速配置

在 Bash / Zsh 终端中,直接运行以下命令即可立即为当前会话注入代理:

export http_proxy="http://127.0.0.1:7890"
export https_proxy="http://127.0.0.1:7890"
export all_proxy="socks5://127.0.0.1:7890"

测试连通性:

curl -I https://www.google.com
# 返回 HTTP/2 200 即代表终端代理生效成功

二、Git 针对 GitHub 单独加速配置

强烈建议不要全局代理所有 git 仓库(防止克隆国内 Gitee 或公司内网 GitLab 时变慢),而是精准只加速 GitHub:

# 仅针对 github.com 域名设置 SOCKS5 代理
git config --global http.https://github.com.proxy "socks5://127.0.0.1:7890"
git config --global https.https://github.com.proxy "socks5://127.0.0.1:7890"

如果使用 SSH 协议克隆,在 ~/.ssh/config 中追加:

Host github.com
    User git
    # Linux / macOS 使用 nc
    ProxyCommand nc -X 5 -x 127.0.0.1:7890 %h %p
    # Windows PowerShell 使用 connect.exe
    # ProxyCommand connect -S 127.0.0.1:7890 %h %p

三、Docker 拉取镜像代理配置 (systemd)

在 Linux 服务器中创建目录与服务注入文件:

sudo mkdir -p /etc/systemd/system/docker.service.d
sudo nano /etc/systemd/system/docker.service.d/http-proxy.conf

填入以下内容(将 IP 改为局域网代理主机 IP):

[Service]
Environment="HTTP_PROXY=http://127.0.0.1:7890"
Environment="HTTPS_PROXY=http://127.0.0.1:7890"
Environment="NO_PROXY=localhost,127.0.0.1,docker-registry.somecorporation.com"

保存后重载服务:

sudo systemctl daemon-reload
sudo systemctl restart docker

此时再次执行 docker pull 即可飞速拉取 Docker Hub 上的全部官方镜像。

💡

常见问题解答 (FAQ)

Q: 终端 export 代理后,使用 git clone 依然报错 LibreSSL SSL_connect: Connection reset by peer? ▼

如果使用的是 [email protected] 这种 SSH 协议而非 https 链接,http_proxy 环境变量对其无效。需在 ~/.ssh/config 中配置 ProxyCommand nc -X 5 -x 127.0.0.1:7890 %h %p 即可打通 SSH 协议代理。

Q: Docker build 构建容器过程中如何正确传递代理? ▼

在执行 docker build 时传入构建参数:docker build --build-arg HTTP_PROXY=http://192.168.1.100:7890 --build-arg HTTPS_PROXY=http://192.168.1.100:7890 -t myimage .(注意宿主机地址需使用局域网 IP 而非 127.0.0.1)。