在 CentOS 上部署和运行 Golang 编译后的程序可以分为几个步骤。以下是一个详细的指南:
首先,确保你已经在 CentOS 上安装了 Golang。如果没有安装,可以按照以下步骤进行安装:
sudo yum install -y golang 然后,编写你的 Golang 程序并保存为 main.go。例如:
package main import "fmt" func main() { fmt.Println("Hello, World!") } 接下来,编译你的程序:
go build -o myapp main.go 这将在当前目录下生成一个名为 myapp 的可执行文件。
确保你的 CentOS 系统已经安装了必要的依赖库。大多数情况下,Golang 编译后的程序不需要额外的依赖库,但如果你使用了某些特定的库,可能需要手动安装这些库。
你可以使用 scp 命令将编译好的可执行文件上传到 CentOS 服务器:
scp myapp user@your_server_ip:/path/to/deploy 在 CentOS 上运行可执行文件之前,需要确保它具有执行权限:
chmod +x /path/to/deploy/myapp 现在,你可以直接运行你的程序:
/path/to/deploy/myapp 如果你希望程序在系统启动时自动运行,可以使用 systemd 来设置开机自启动。
首先,创建一个新的 systemd 服务文件:
sudo vi /etc/systemd/system/myapp.service 在文件中添加以下内容:
[Unit] Description=My Golang Application After=network.target [Service] ExecStart=/path/to/deploy/myapp Restart=always User=your_user Group=your_group [Install] WantedBy=multi-user.target 保存并退出编辑器。
然后,启用并启动服务:
sudo systemctl daemon-reload sudo systemctl enable myapp.service sudo systemctl start myapp.service 你可以使用以下命令来监控和管理你的服务:
查看服务状态:
sudo systemctl status myapp.service 停止服务:
sudo systemctl stop myapp.service 重启服务:
sudo systemctl restart myapp.service 通过以上步骤,你应该能够在 CentOS 上成功部署和运行你的 Golang 程序。