全局代理(让系统所有流量走代理)、特定应用代理(如 Docker、Yum/Apt、Git 等)以及 反向代理(如 Nginx 对外提供服务)。
以下是针对 Linux 服务器(以 CentOS/Ubuntu 为例)设置正向代理(即服务器通过代理访问外网)的常见方法:
临时设置(当前 Shell 会话有效)
如果你只是临时需要,可以直接在终端中设置环境变量:
# 假设代理地址为 http://127.0.0.1:7890 export http_proxy=http://127.0.0.1:7890 export https_proxy=http://127.0.0.1:7890 # 如果代理需要认证 export http_proxy=http://user:password@127.0.0.1:7890 export https_proxy=http://user:password@127.0.0.1:7890
注意:这种方式只对当前终端窗口有效,关闭后失效。
永久设置(全局生效)
方法 1:修改 /etc/environment(推荐,适用于大多数命令)
此文件会被 PAM 模块读取,适用于图形界面和大多数命令行工具。
-
编辑文件:
sudo nano /etc/environment -
http_proxy="http://127.0.0.1:7890" https_proxy="http://127.0.0.1:7890" ftp_proxy="http://127.0.0.1:7890"
-
保存退出,然后重启服务器或重新登录会话使配置生效。
方法 2:修改 /etc/profile.d/proxy.sh(适用于 bash/shell)
创建一个脚本文件,确保所有用户登录时都能加载代理设置。
-
创建文件:
sudo nano /etc/profile.d/proxy.sh
export http_proxy="http://127.0.0.1:7890" export https_proxy="http://127.0.0.1:7890" export no_proxy="localhost,127.0.0.1,::1"
-
赋予执行权限:
sudo chmod +x /etc/profile.d/proxy.sh
-
立即生效:
source /etc/profile.d/proxy.sh
特定工具设置代理
有些工具不读取全局环境变量,需要单独配置。
Yum / DNF(CentOS/RHEL)
编辑 /etc/yum.conf:
[main] proxy=http://127.0.0.1:7890
Apt(Ubuntu/Debian)
创建配置文件 /etc/apt/apt.conf.d/99proxy:
sudo nano /etc/apt/apt.conf.d/99proxy
添加:
Acquire::http::Proxy "http://127.0.0.1:7890";
Acquire::https::Proxy "http://127.0.0.1:7890";
Git
git config --global http.proxy http://127.0.0.1:7890 git config --global https.proxy http://127.0.0.1:7890
取消代理:
git config --global --unset http.proxy git config --global --unset https.proxy
Docker
Docker 默认不使用系统代理,需要单独配置。
-
创建或编辑
/etc/systemd/system/docker.service.d/http-proxy.conf:[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:
sudo systemctl daemon-reload sudo systemctl restart docker
Curl
编辑 ~/.curlrc 或 /etc/curlrc:
proxy = "http://127.0.0.1:7890"
验证代理是否生效
# 检查环境变量 echo $http_proxy echo $https_proxy # 测试访问 curl -I https://www.google.com
如果返回 HTTP 200 或 301/302 重定向信息,说明代理设置成功。
注意事项
- 代理协议:确保你使用的代理是 HTTP/HTTPS 类型,如果是 SOCKS5 代理,需将
http_proxy改为socks5://前缀。 - 无代理列表:务必设置
no_proxy,避免访问内网地址时经过代理导致失败。export no_proxy="localhost,127.0.0.1,192.168.,10."
- 安全性:在生产环境中,建议限制代理访问权限,避免内部流量泄露。
如果你指的是反向代理(如用 Nginx 将外部请求转发到内部服务),请告诉我,我可以提供 Nginx 配置示例。
首发原创文章,作者:世雄 - 原生数据库架构专家,如若转载,请注明出处:https://idctop.com/article/476587.html



