在 CentOS 上运行 Go(Golang)程序,通常分为 安装 Go 环境 和 运行/编译 Go 程序 两部分。下面给你一份清晰、可直接照做的指南。
cd /usr/local
sudo curl -OL https://go.dev/dl/go1.22.5.linux-amd64.tar.gz
sudo tar -C /usr/local -xzf go1.22.5.linux-amd64.tar.gz
~/.bashrc 或 ~/.profile:export PATH=$PATH:/usr/local/go/bin
export GOPATH=$HOME/go
export PATH=$PATH:$GOPATH/bin
使配置生效:
source ~/.bashrc
go version
输出类似:
go version go1.22.5 linux/amd64
sudo yum install golang -y
go version
⚠️ CentOS 自带源中的 Go 版本通常偏低,不推荐生产使用
mkdir ~/hello && cd ~/hello
cat > main.go <<EOF
package main
import "fmt"
func main() {
fmt.Println("Hello, CentOS!")
}
EOF
go run main.go
go build -o hello main.go
./hello
nohup ./hello > app.log 2>&1 &
创建服务文件:
sudo vi /etc/systemd/system/hello.service
内容示例:
[Unit]
Description=Go Hello Service
After=network.target
[Service]
ExecStart=/root/hello/hello
WorkingDirectory=/root/hello
Restart=always
User=root
[Install]
WantedBy=multi-user.target
启动:
sudo systemctl daemon-reload
sudo systemctl start hello
sudo systemctl enable hello
sudo firewall-cmd --permanent --add-port=8080/tcp
sudo firewall-cmd --reload
go mod init hello
go mod tidy
如果你愿意,可以告诉我:
我可以给你更贴合的方案。