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

杀掉进程

ps -ef|grep "./main"|grep -v grep|awk '{print $2}'|xargs kill -9

基于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程序完成!

原文地址:https://www.cnblogs.com/niuben/p/14298971.html