centos

Golang项目在CentOS如何打包部署

小樊
52
2025-05-29 09:10:13
栏目: 编程语言

在CentOS上打包和部署Golang项目,可以按照以下步骤进行:

1. 安装Go环境

首先,确保你的CentOS系统上已经安装了Go环境。如果没有安装,可以通过以下命令安装:

sudo yum install golang

2. 配置Go环境变量

编辑/etc/profile文件,添加Go的环境变量:

export GOROOT=/usr/local/go
export GOPATH=/home/yourusername/go
export PATH=$PATH:$GOROOT/bin:$GOPATH/bin

然后,使配置生效:

source /etc/profile

3. 编译Golang项目

进入你的项目目录,使用go build命令编译项目。假设你的项目名为myapp,并且位于/home/yourusername/myapp目录下:

cd /home/yourusername/myapp
go build -o myapp

这将在当前目录下生成一个名为myapp的可执行文件。

4. 打包项目

如果你需要将整个项目打包成一个压缩文件,可以使用tar命令:

cd /home/yourusername
tar -czvf myapp.tar.gz myapp

这将在/home/yourusername目录下生成一个名为myapp.tar.gz的压缩文件。

5. 上传打包文件到CentOS服务器

你可以使用scp命令将打包文件上传到CentOS服务器:

scp myapp.tar.gz yourusername@yourserver:/home/yourusername

6. 在CentOS服务器上解压和部署

登录到你的CentOS服务器,然后解压并部署项目:

cd /home/yourusername
tar -xzvf myapp.tar.gz
cd myapp
./myapp

7. 设置开机自启动(可选)

如果你希望项目在系统启动时自动运行,可以使用systemd服务来实现。

创建一个新的服务文件:

sudo vi /etc/systemd/system/myapp.service

在文件中添加以下内容:

[Unit]
Description=My Golang Application
After=network.target

[Service]
User=yourusername
Group=yourgroup
ExecStart=/home/yourusername/myapp/myapp
Restart=always

[Install]
WantedBy=multi-user.target

保存并退出编辑器,然后启用并启动服务:

sudo systemctl daemon-reload
sudo systemctl enable myapp.service
sudo systemctl start myapp.service

现在,你的Golang项目已经成功打包并在CentOS服务器上部署运行了。

0
看了该问题的人还看了