在 CentOS 上配置 / 使用 Golang,常见“坑”主要集中在 系统版本、环境变量、权限、代理、SELinux、Cgo 等方面。下面按实际使用场景给你总结一份「避坑指南」。
✅ 建议:
yum install golang
问题:
✅ 正确方式:
wget https://go.dev/dl/go1.22.linux-amd64.tar.gz
tar -C /usr/local -xzf go1.22.linux-amd64.tar.gz
很多人乱配:
export GOROOT=/usr/local/go
export GOPATH=$HOME/go
export PATH=$PATH:$GOROOT/bin
⚠ 坑:
go: command not found✅ 推荐最小配置(写入 ~/.bashrc 或 /etc/profile):
export PATH=$PATH:/usr/local/go/bin
默认:
GOPROXY=https://proxy.golang.org
国内网络基本超时。
✅ 解决:
go env -w GOPROXY=https://goproxy.cn,direct
或:
export GOPROXY=https://goproxy.cn,direct
$HOME/go 被 root 拥有✅ 建议:
go env -w GOMODCACHE=/data/go/mod
报错类似:
CGO_ENABLED=1: gcc: command not found
✅ 解决:
yum install -y gcc glibc-devel
或禁用 Cgo(纯 Go):
CGO_ENABLED=0 go build
✅ 排查:
getenforce
✅ 临时关闭(不推荐生产):
setenforce 0
✅ 正确方式:
semanage port -a -t http_port_t -p tcp 8080
firewall-cmd --permanent --add-port=8080/tcp
firewall-cmd --reload
✅ 推荐 systemd:
[Unit]
Description=go app
After=network.target
[Service]
User=app
ExecStart=/data/app/server
Restart=always
[Install]
WantedBy=multi-user.target
Go 程序时间不对:
ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
✅ 不要 yum 装 Go
✅ 不要乱设 GOROOT/GOPATH
✅ 必须配 GOPROXY
✅ Cgo 要装 gcc
✅ 注意 SELinux / firewalld
✅ 用 systemd 管理进程
如果你愿意,可以告诉我:
我可以直接帮你“对症排坑”。