在CentOS上为Golang项目打包并部署,可以遵循以下最佳实践:
/usr/local
。bin
目录添加到PATH
环境变量中。# 示例命令
wget https://golang.google.cn/dl/go1.18.linux-amd64.tar.gz
tar -C /usr/local -xzf go1.18.linux-amd64.tar.gz
echo 'export PATH=$PATH:/usr/local/go/bin' >> /etc/profile
source /etc/profile
go mod init example.com/myapp
go build
命令编译项目,生成可执行文件。可以使用-ldflags
参数来去除符号表和调试信息,以减小文件大小。CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -a -installsuffix cgo -o myapp main.go
scp
、rsync
等工具。scp myapp user@your_server_ip:/path/to/destination
chmod +x /path/to/destination/myapp
nohup
命令使程序在后台运行,并输出日志到文件。nohup ./myapp > log.txt 2>&1 &
/etc/systemd/system/
目录下创建一个服务文件,例如myapp.service
。[Unit]
Description=My Go Application
After=syslog.target
[Service]
User=root
WorkingDirectory=/path/to/destination
ExecStart=/path/to/destination/myapp
Restart=always
[Install]
WantedBy=multi-user.target
systemctl daemon-reload
systemctl start myapp.service
systemctl enable myapp.service
go mod tidy
命令来清理和更新依赖。通过以上步骤,你可以在CentOS上为Golang项目打包并部署一个高效、可靠的应用程序。