在CentOS上部署Golang项目通常涉及以下几个步骤:
- 安装Go环境:
- 首先,从Go官方网站下载适合CentOS的Go语言包,并使用
wget
命令进行安装。 - 解压下载的.tar.gz文件到
/usr/local
目录下。 - 配置环境变量,将Go的可执行文件路径添加到系统环境变量中。可以通过编辑
/etc/profile
文件来完成这一步。
- 配置环境变量:
- 编辑
~/.bashrc
文件,添加以下内容:
export GOROOT=/usr/local/goexport GOPATH=$HOME/goexport PATH=$PATH:$GOROOT/bin:$GOPATH/bin
- 保存文件后,运行
source ~/.bashrc
使环境变量生效。
- 编写和编译Go应用程序:
- 在项目目录下编写你的Go应用程序代码。
- 使用
go build
命令编译应用程序,生成可执行文件。
- 使用systemd管理服务(可选但推荐):
- 创建一个systemd服务文件,例如
/etc/systemd/system/myapp.service
,并添加以下内容:
[Unit]Description=My Go ApplicationAfter=syslog.target[Service]Type=simpleUser=rootWorkingDirectory=/path/to/your/appExecStart=/path/to/your/app/myappRestart=alwaysEnvironment=ENV_VAR1=value1 ENV_VAR2=value2[Install]WantedBy=multi-user.target
- 加载并启动服务:
systemctl daemon-reloadsystemctl start myapp.servicesystemctl status myapp.service
- 设置开机自启动:
systemctl enable myapp.service
- 配置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 nginxsystemctl status nginx
- 访问你的应用:
- 配置好Nginx后,你可以通过服务器的IP地址或域名来访问你的Go应用程序。
请注意,上述步骤中的路径和文件名应根据你的实际情况进行调整。此外,确保你的防火墙允许外部访问你设置的端口。