Proxy
在远程服务器上使用本地代理
背景
实验室服务器通常连接校园网,有时 443 端口被限制,导致无法访问外部网站。为了解决这个问题,我们可以在本地机器上设置一个代理服务器,并通过 SSH 隧道将其转发到远程服务器。
SSH 隧道设置
以 clash 为例,设置 http 代理端口为 7890
端口流量转发
在连接远程服务器时,可以使用以下命令将本地的 7890 端口转发到远程服务器的 1080 端口:
ssh -N -f -L 1080:127.0.0.1:7890 user@remote-server
或者通过 vscode 的 Remote SSH 插件,配置 ~/.ssh/config 文件:
Host remote-server
HostName remote-server-address
User your-username
RemoteForward 1080 127.0.0.1:7890
即将远程服务器的 1080 端口流量通过 SSH 转发到本地的 7890 端口(运行有代理的本地端口)。
设置 http 代理
在远程服务器上,设置环境变量以使用代理:
export http_proxy="http://127.0.0.1:1080"
export https_proxy="http://127.0.0.1:1080"
可以将上述命令添加到 ~/.bashrc 或 ~/.zshrc 文件中,以便每次登录时自动设置。
验证
可以通过以下命令验证代理是否设置成功:
curl-I https://update.code.visualstudio.com
# 成功返回
# Hello from VS Code!
# 或者
curl-I https://www.google.com
注意事项
- 确保本地机器上的代理服务器(如 clash)正在运行,并监听正确的端口。
- 上述的端口号(1080 和 7890)可以根据实际情况进行调整,但需要确保它们在本地和远程服务器上没有被其他服务占用。尤其是不同使用相同的端口号,
Remote SSH可能会自动在本地端口上进行转发,如果使用相同端口号,可能导致两个程序监听同一个端口,挤占代理服务器程序导致冲突。
Docker 代理设置
docker daemon 需要单独设置代理,可以通过创建或编辑 /etc/systemd/system/docker.service.d/http-proxy.conf 文件来实现:
# 创建 systemd 目录(如果不存在)
sudo mkdir -p /etc/systemd/system/docker.service.d
# 创建或编辑代理配置文件
sudo vim /etc/systemd/system/docker.service.d/http-proxy.conf
在文件中添加以下内容:
[Service]
Environment="HTTP_PROXY=http://proxy.example.com:8080/"
Environment="HTTPS_PROXY=http://proxy.example.com:8080/"
Environment="NO_PROXY=localhost,127.0.0.1,.docker.internal,.example.com"
例如:
[Service]
Environment="HTTP_PROXY=http://127.0.0.1:1080/"
Environment="HTTPS_PROXY=http://127.0.0.1:1080/"
Environment="NO_PROXY=localhost,127.0.0.1,.docker.internal,.local,host.docker.internal"
然后重新加载 systemd 配置并重启 Docker 服务:
sudo systemctl daemon-reload
sudo systemctl restart docker
验证代理是否生效:
sudo systemctl show --property Environment docker
# 应该看到设置的 HTTP_PROXY 和 HTTPS_PROXY
# 拉取 hello-world 镜像测试
sudo docker pull hello-world