温馨提示×

CentOS Golang项目如何部署

小樊
66
2025-03-07 10:58:07
栏目: 编程语言

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

  1. 安装Go环境
  • 首先,从Go官方网站下载适合CentOS的Go语言包,并使用wget命令进行安装。
  • 解压下载的.tar.gz文件到/usr/local目录下。
  • 配置环境变量,将Go的可执行文件路径添加到系统环境变量中。可以通过编辑/etc/profile文件来完成这一步。
  1. 配置环境变量
  • 编辑~/.bashrc文件,添加以下内容:
export GOROOT=/usr/local/go export GOPATH=$HOME/go export PATH=$PATH:$GOROOT/bin:$GOPATH/bin 
  • 保存文件后,运行source ~/.bashrc使环境变量生效。
  1. 编写和编译Go应用程序
  • 在项目目录下编写你的Go应用程序代码。
  • 使用go build命令编译应用程序,生成可执行文件。
  1. 使用systemd管理服务(可选但推荐):
  • 创建一个systemd服务文件,例如/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 Environment=ENV_VAR1=value1 ENV_VAR2=value2 [Install] WantedBy=multi-user.target 
  • 加载并启动服务:
systemctl daemon-reload systemctl start myapp.service systemctl status myapp.service 
  • 设置开机自启动:
systemctl enable myapp.service 
  1. 配置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服务:
systemctl restart nginx systemctl status nginx 
  1. 访问你的应用
  • 配置好Nginx后,你可以通过服务器的IP地址或域名来访问你的Go应用程序。

请注意,上述步骤中的路径和文件名应根据你的实际情况进行调整。此外,确保你的防火墙允许外部访问你设置的端口。

0