在CentOS系統上部署Golang項目通常涉及以下幾個步驟:
首先,需要在CentOS系統上安裝Go語言環境??梢酝ㄟ^以下命令來安裝Go:
sudo yum install golang
或者,你可以從Go官方網站下載適合CentOS版本的安裝包進行安裝:
wget https://golang.google.cn/dl/go1.16.5.linux-amd64.tar.gz
tar -C /usr/local -zxvf go1.16.5.linux-amd64.tar.gz
安裝完成后,配置環境變量:
echo 'export PATH=$PATH:/usr/local/go/bin' >> ~/.bashrc
source ~/.bashrc
go version
在項目目錄下使用go build
命令編譯你的Go應用程序,生成一個可執行文件。例如,如果你的項目入口文件是main.go
,則命令如下:
go build -o myapp main.go
為了確保你的Go應用程序在服務器重啟后自動啟動,可以使用systemd來管理你的服務。首先,創建一個systemd服務文件,例如/etc/systemd/system/myapp.service
:
[Unit]
Description=My Go Application
After=network.target
[Service]
User=your_user
WorkingDirectory=/path/to/your/app
ExecStart=/path/to/your/app/myapp
Restart=always
Environment=APP_ENV=production
[Install]
WantedBy=multi-user.target
然后,重新加載systemd配置并啟動服務:
sudo systemctl daemon-reload
sudo systemctl start myapp.service
sudo systemctl enable myapp.service
如果你希望使用Nginx作為反向代理來處理HTTP請求,可以配置Nginx來轉發請求到你的Go應用程序。首先,安裝Nginx:
sudo yum install nginx
然后,編輯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以應用配置:
sudo systemctl restart nginx
為了更方便地管理你的Go應用程序,可以使用PM2進程管理器。首先,安裝PM2:
sudo npm install -g pm2
然后,使用PM2啟動你的應用程序:
pm2 start myapp.js
PM2可以幫助你管理、監控和自動重啟你的應用程序。
以上步驟是在CentOS系統上部署Golang項目的基本流程。根據你的具體需求,可能還需要進行其他配置,例如數據庫連接、環境變量設置等。