如何在 Linux 系统中使用代理服务器

First Post:

Last Update:


在进行下面的步骤之前,首先需要搞清楚你的代理服务器 IP、端口、协议,以及用户名和密码(如果有的话)是什么。

普通程序

一般情况下,我们使用环境变量指定代理服务器:

1
2
3
export http_proxy="http://username:password@proxyServer:port/"
export https_proxy="http://username:password@proxyServer:port/"
export ftp_proxy="http://username:password@proxyServer:port/"

这三条命令分别指定了 HTTP、HTTPS 和 FTP 的代理服务器。
username 表示代理服务器的用户名
password 表示密码
如果没有验证,以上两项可以去掉。
proxyServer 表示主机名
port 表示端口
简单的示例:

1
2
3
export http_proxy="http://127.0.0.1:8080/"
export https_proxy="http://127.0.0.1:8080/"
export ftp_proxy="http://127.0.0.1:8080/"

程序会读取这些环境变量,并通过指定的代理服务器访问互联网。

不能使用环境变量的程序

有些程序不会读取这些环境变量,它们的代理需要手动指定。这里有一些常用程序:

Git

Git 的代理由它自己的设置决定。

1
2
3
## HTTP
git config --global http.proxy "http://127.0.0.1:8080"
git config --global https.proxy "http://127.0.0.1:8080"
1
2
3
## SOCKS5
git config --global http.proxy "socks5://127.0.0.1:1080"
git config --global https.proxy "socks5://127.0.0.1:1080"

--global 表示全局设置;HTTP 和 SOCKS5 选一种设置即可。
也可以单独为某个网站指定:

1
2
git config --global "http.https://github.com.proxy" "http://127.0.0.1:8080"
git config --global "https.https://github.com.proxy" "http://127.0.0.1:8080"

SSH 的代理在 SSH 配置文件中,需编辑 ~/.ssh/config
请参考 SSH 配置文件

Snap

Snap 的代理写在设置里面。

1
2
sudo snap set system proxy.http="http://127.0.0.1:8080"
sudo snap set system proxy.https="http://127.0.0.1:8080"

或者考虑到 Snap 的 snapd 由 systemd 启动,所以不受上述环境变量的影响,也可以直接修改 service 文件(网上大部分是这种方法):

1
sudo systemctl edit snapd.service

添加如下内容:

1
2
3
[Service]
Environment=http_proxy=http://proxy:port
Environment=https_proxy=http://proxy:port

随后重启 systemd 和 snapd 即可。

Docker

与 Snap 同理,由 systemd 启动的 dockerd 执行实际的操作。
容器使用的代理写在 ~/.docker/config.json 中,这里不考虑。
请参考上面 Snap 部分,修改 service 文件并重启 dockerd 服务即可。
注意:如果你的 Docker 是通过 Snap 安装的,那么它的服务名称为 snap.docker.dockerd ,而不是普通的 docker