GitLab Runner连接被拒:配置代理后仍无法访问pip请求求助
问题背景
已在GitLab Runner的systemd配置中添加代理环境变量:
[Service] Environment="HTTP_PROXY=http://squidproxy.example.com:3128/" Environment="HTTPS_PROXY=http://squidproxy.example.com:3128/" Environment="NO_PROXY=gitlab.example.com"
但构建时pip仍无法连接外部资源,日志报错:
WARNING: Retrying (Retry(total=1, connect=None, read=None,
redirect=None, status=None)) after connection broken by
'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection
object at 0x7f10bd297880>: Failed to establish a new connection:
[Errno 111] Connection refused')': /simple/virtualenv/
怀疑构建过程未加载配置的代理环境变量。
排查与解决步骤
1. 确认systemd配置生效并重启Runner
修改systemd配置后,必须重新加载配置并重启服务,否则新环境变量不会生效:
sudo systemctl daemon-reload sudo systemctl restart gitlab-runner
执行以下命令验证Runner进程是否已加载代理变量:
cat /proc/$(pgrep gitlab-runner)/environ | tr '\0' '\n' | grep -E "(HTTP_PROXY|HTTPS_PROXY|NO_PROXY)"
如果无对应输出,检查systemd配置文件路径是否正确(通常为/etc/systemd/system/gitlab-runner.service或/usr/lib/systemd/system/gitlab-runner.service)。
2. 在Runner配置文件中显式传递代理变量
若使用Docker executor,systemd的环境变量不会自动传递到构建容器,需在config.toml中配置:
打开Runner配置文件(通常在/etc/gitlab-runner/config.toml),在[[runners]]段内添加:
environment = ["HTTP_PROXY=http://squidproxy.example.com:3128/", "HTTPS_PROXY=http://squidproxy.example.com:3128/", "NO_PROXY=gitlab.example.com"]
修改后重启Runner:
sudo systemctl restart gitlab-runner
3. 在CI/CD流水线中直接配置代理
如果前两种方法无效,可在.gitlab-ci.yml的job中显式设置变量:
build: script: - export HTTP_PROXY=http://squidproxy.example.com:3128/ - export HTTPS_PROXY=http://squidproxy.example.com:3128/ - export NO_PROXY=gitlab.example.com - pip install -r requirements.txt
也可直接生成pip配置文件:
mkdir -p ~/.config/pip echo -e "[global]\nproxy = http://squidproxy.example.com:3128/\n[install]\ntrusted-host = pypi.org files.pythonhosted.org" > ~/.config/pip/pip.conf
4. 验证代理服务器的可用性
在Runner服务器上直接测试代理能否访问PyPI:
curl -x http://squidproxy.example.com:3128/ https://pypi.org/simple/virtualenv/
如果无法访问,说明代理服务器存在端口未开放、IP拦截或规则限制等问题。
内容的提问来源于stack exchange,提问作者Brandon Kauffman

