在CentOS上部署Golang项目,你需要遵循以下步骤:
首先,确保你已经在CentOS上安装了Golang。如果还没有安装,可以通过以下命令安装:
sudo yum install golang
然后,设置GOROOT和GOPATH环境变量。编辑~/.bashrc文件,添加以下内容:
export GOROOT=/usr/lib/golang
export GOPATH=$HOME/go
export PATH=$PATH:$GOROOT/bin:$GOPATH/bin
保存文件并运行source ~/.bashrc使环境变量生效。
在项目根目录下,使用go build命令编译项目。这将生成一个可执行文件。例如:
go build -o myapp
这将在当前目录下生成一个名为myapp的可执行文件。
如果你的项目有外部依赖,请确保已经使用go mod命令下载并安装了所有依赖。例如:
go mod tidy
如果你想使用Nginx或Apache作为反向代理,可以按照以下步骤操作:
sudo yum install nginx
或
sudo yum install httpd
/etc/nginx/conf.d/myapp.conf文件,添加以下内容:server {
listen 80;
server_name myapp.example.com;
location / {
proxy_pass http://localhost:8080;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
对于Apache,编辑/etc/httpd/conf.d/myapp.conf文件,添加以下内容:
<VirtualHost *:80>
ServerName myapp.example.com
ProxyPreserveHost On
ProxyPass / http://localhost:8080/
ProxyPassReverse / http://localhost:8080/
</VirtualHost>
sudo systemctl restart nginx
或
sudo systemctl restart httpd
现在你可以运行编译好的Golang应用程序了:
./myapp
或者,你可以使用nohup命令在后台运行应用程序,以便在关闭终端时继续运行:
nohup ./myapp &
至此,你已经成功在CentOS上部署了Golang项目。