在 CentOS 上配置 Golang 环境时,确实有一些常见的“坑点”,尤其是和版本、权限、环境变量的细节有关。下面按「最容易踩坑」的顺序给你梳理一下。
CentOS(尤其是 7)通过 yum 安装的 Go 版本非常旧:
yum install golang
# 可能是 go1.13 甚至更早
很多新项目(如 Gin、K8s、云原生组件)要求 Go 1.18+。
✅ 不要使用 yum 安装 Go
从官网下载:
wget https://go.dev/dl/go1.22.5.linux-amd64.tar.gz
sudo rm -rf /usr/local/go
sudo tar -C /usr/local -xzf go1.22.5.linux-amd64.tar.gz
很多人写在 ~/.bashrc,但:
sudo 执行时环境变量丢失编辑:
vim ~/.bashrc
加入:
export GOROOT=/usr/local/go
export GOPATH=$HOME/go
export PATH=$PATH:$GOROOT/bin:$GOPATH/bin
然后:
source ~/.bashrc
✅ 如果是 系统服务 / CI,建议写在:
/etc/profile.d/go.sh
root 编译,再切普通用户运行 → 权限不足go mod download 写入系统目录失败✅ 永远用普通用户编译 Go 程序
✅ 不要把 GOPATH 设在 /root
export GOPATH=$HOME/go
go: module fetch failed
CentOS 默认网络环境可能访问不了 proxy.golang.org
go env -w GO111MODULE=on
go env -w GOPROXY=https://goproxy.cn,direct
./app 提示 Permission deniedls -l 看起来权限正常SELinux 拦截
getenforce
setenforce 0
或给文件加执行上下文:
chcon -t bin_t app
Go 服务起来了,但外部访问不了
firewall-cmd --list-ports
开放端口:
firewall-cmd --add-port=8080/tcp --permanent
firewall-cmd --reload
nohup 而不是 systemd[Unit]
Description=Go App
After=network.target
[Service]
User=appuser
WorkingDirectory=/home/appuser/app
ExecStart=/home/appuser/app/server
Environment=GO_ENV=production
[Install]
WantedBy=multi-user.target
使用 sqlite、bcrypt 等需要 CGO:
exec: "gcc": executable file not found
yum install -y gcc glibc-devel
CentOS 老系统运行新版 Go 编译程序报:
GLIBC_2.28 not found
CGO_ENABLED=0 go build
✅ 不用 yum 的 go
✅ 用官方 tar 包
✅ 普通用户编译
✅ 配置 GOPROXY
✅ 注意 SELinux / firewall
✅ systemd 明确环境变量
如果你愿意,我可以: