centos

CentOS中Go语言项目如何部署

小樊
45
2025-05-14 21:42:56
栏目: 编程语言

在CentOS上部署Go语言项目通常包括以下几个步骤:

1. 安装Go环境

首先,从Go官方网站下载适合CentOS的Go语言包,并使用wget命令进行安装。例如,下载Go 1.18版本:

wget https://golang.google.cn/dl/go1.18.linux-amd64.tar.gztar -C /usr/local -xzf go1.18.linux-amd64.tar.gz

2. 配置环境变量

安装完成后,需要配置系统环境变量,以便在全局使用Go。可以新增 /etc/profile.d/go.sh 文件,将以下内容写入:

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

然后执行以下命令使更改生效:

source /etc/profile.d/go.sh

验证安装是否成功,可以输入:

go version

如果输出了Go的版本信息,说明安装成功。

3. 编译Go程序

使用 go build 命令对应用程序进行编译。例如,编译一个名为 main.go 的程序:

go build main.go

4. 使用systemd管理服务(可选但推荐)

为了系统服务的管理,可以使用systemd将Go程序注册为一个服务,然后实现开机自启动。

编写unit文件

/etc/systemd/system/ 目录下,新建一个名为 myapp.service 的服务文件,填入以下内容:

[Unit]
Description=My Go Application
After=syslog.target

[Service]
Type=simple
User=root
WorkingDirectory=/path/to/your/app
ExecStart=/path/to/your/app/myapp
Restart=always
RestartSec=5s

[Install]
WantedBy=multi-user.target

加载并启动服务

执行以下命令加载服务文件并启动服务:

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

设置开机自启动

使用以下命令设置开机自启动:

sudo systemctl enable myapp.service

5. 运行和监控应用

使用 nohup 命令在后台运行应用,并将输出重定向到日志文件:

nohup ./myapp > nohup.log 2>&1 &

可以使用 netstat 命令查找指定端口的进程:

netstat -tunlp | grep 9001

在生产环境中,建议使用更温和的方式来重启服务,而不是使用 kill -9

6. 配置Nginx反向代理(可选)

如果你希望使用Nginx作为反向代理来处理HTTP请求,可以编辑Nginx配置文件(通常位于 /etc/nginx/nginx.conf/etc/nginx/conf.d/default.conf),并添加以下内容:

server {
    listen 80;
    server_name your_domain_or_ip;

    location / {
        proxy_pass http://localhost:8080; # 假设你的Go应用运行在8080端口
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

重新加载Nginx配置并启动Nginx服务:

sudo systemctl restart nginx
sudo systemctl status nginx

配置好Nginx后,你可以通过服务器的IP地址或域名来访问你的Go应用程序。请注意,上述步骤中的路径和文件名应根据你的实际情况进行调整。此外,确保你的防火墙允许外部访问你设置的端口。

通过以上步骤,你可以在CentOS系统上顺利部署和配置Go语言环境,并开始进行Go语言的开发工作。如果有任何问题,可以参考相关的官方文档或社区资源。

0
看了该问题的人还看了