温馨提示×

Golang项目在CentOS如何部署

小樊
34
2025-03-05 10:27:54
栏目: 编程语言
GO开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

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

1. 安装Go环境

首先,需要在CentOS系统上安装Go语言环境。可以通过以下命令来安装Go:

sudo yum install golang

安装完成后,可以通过运行以下命令来验证Go是否已经成功安装:

go version

如果安装成功,将显示Go的版本信息。

2. 配置Go环境变量

为了使Go命令在终端中能够正常运行,需要将Go的可执行文件路径添加到系统环境变量中。可以通过以下命令进行配置:

sudo vi /etc/profile

在打开的文件中,在最后添加以下内容:

export PATH=$PATH:/usr/local/go/bin

保存文件并退出编辑器。然后通过以下命令使环境变量配置生效:

source /etc/profile

3. 编译Go项目

在项目目录下使用go build命令进行编译,生成适用于Linux系统的可执行文件。例如,如果你的项目入口文件是main.go,则可以使用以下命令进行编译:

GOOS=linux GOARCH=amd64 go build -o myapp main.go

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

4. 配置systemd服务(可选)

为了实现服务的开机自启动和管理,可以使用systemd。首先,创建一个systemd服务文件,例如/etc/systemd/system/myapp.service,并添加以下内容:

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

[Service]
User=root
WorkingDirectory=/path/to/your/app
ExecStart=/path/to/your/app/myapp
Restart=always
Environment=APP_ENV=production

[Install]
WantedBy=multi-user.target

然后,加载并启动服务:

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

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

如果你希望使用Nginx作为反向代理来运行你的Go应用,可以按照以下步骤进行配置:

  • 安装Nginx:
sudo yum install nginx
  • 编辑Nginx配置文件,例如/etc/nginx/conf.d/myapp.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以应用配置:
sudo systemctl restart nginx

6. 运行应用

最后,你可以通过以下命令来运行你的Go应用:

./myapp

或者,如果你已经配置了systemd服务,可以使用以下命令来启动、停止或重启服务:

sudo systemctl start myapp.service
sudo systemctl stop myapp.service
sudo systemctl restart myapp.service

以上步骤涵盖了在CentOS上部署Golang项目的基本流程,包括安装Go环境、配置环境变量、编译项目、配置systemd服务以及运行应用。根据具体项目的需求,可能还需要进行其他配置,例如数据库连接、配置文件管理等。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:Golang 项目在 CentOS 上的打包与部署技巧

0