1. 程式人生 > 實用技巧 >linux部署go專案

linux部署go專案

直接部署:

1、將程式所需要的檔案如配置檔案和生成的可執行檔案拷貝到linux中

2、直接執行./main命令,啟動程式 (main是go編譯生成的可執行檔案)

如果報Permission denied錯誤,將可執行檔案賦予可執行許可權

chmod -R 755 main

在後臺啟動程式

./main這種啟動方法在控制檯退出時程式會停止,我們可以用nohup ./main &命令讓程式在後臺執行

nohup ./main &

如果需要記錄日誌的話,可以這樣使用

nohup ./main > logs/app.log 2>&1 &

nohup 需要執行的命令 >日誌檔案路徑 2>&1 &

檢視程式是否正常執行

ps aux | grep main

基於nginx部署:

首先啟動你的go服務,可參照上面直接部署

在使用nginx 部署時,首先要明白nginx 反向代理的原理。推薦看下Nginx 極簡教程

反向代理是指以代理伺服器來接受網路上的連線請求,然後將請求轉發給內部網路上的伺服器,並將從伺服器上得到的結果返回給請求連線的客戶端,此時代理伺服器對外就表現為一個反向代理伺服器。(來自百科)

配置 hosts

由於需要用本機作為演示,因此先把對映配上去,開啟 /etc/hosts,增加內容:

127.0.0.1       api.blog.com

配置 nginx.conf

開啟 nginx 的配置檔案 nginx.conf(我的是 /usr/local/etc/nginx/nginx.conf),我們做了如下事情:

增加 server 片段的內容,設定 server_name 為 api.blog.com 並且監聽 8081 埠,將所有路徑轉發到 http://127.0.0.1:8000/

worker_processes  1;

events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    sendfile        on;
    keepalive_timeout  65;

    server {
        listen       8081;
        server_name  api.blog.com;

        location / {
            proxy_pass http://127.0.0.1:8000/;
        }
    }
}

重啟 nginx

$ nginx -t
nginx: the configuration file /usr/local/etc/nginx/nginx.conf syntax is ok
nginx: configuration file /usr/local/etc/nginx/nginx.conf test is successful
$ nginx -s reload

訪問介面

這樣就實現了一個簡單的反向代理,基於nginx部署go程式完成!