ubuntu 18.04 环境下搭建 nginx 服务,跑 go 程序;
参考地址:
如何在Ubuntu 18.04上使用Nginx部署Go Web应用程序
https://www.howtoing.com/how-to-deploy-a-go-web-application-using-nginx-on-ubuntu-18-04
- 安装 nginx
sudo apt-get install nginx
sudo systemctl start nginx
sudo systemctl stop nginx
sudo systemctl restart nginx
防火墙端口的设置
iptables -I INPUT 5 -p tcp --dport 80 -j ACCEPT
- golang 安装
add-apt-repository ppa:longsleep/golang-backports
apt-get update
sudo apt-get install golang-go
鉴定是否安装成功
go version
配置信息查看
go env
$GOPATH
- 部署 go 程序
/root/go/main.go
package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello World")
})
http.HandleFunc("/greet/", func(w http.ResponseWriter, r *http.Request) {
name := r.URL.Path[len("/greet/"):]
fmt.Fprintf(w, "Hello %s\n", name)
})
http.ListenAndServe(":9990", nil)
}
然后编译可执行文件:
go build main.go
设置系统单元文件:
在 /lib/systemd/system/ 下创建 goweb.service 文件,并写以下内容
[Unit]
Description=goweb
[Service]
Type=simple
Restart=always
RestartSec=5s
ExecStart=/root/go/main
[Install]
WantedBy=multi-user.target
启动服务:
sudo service goweb start
sudo service goweb stop
sudo service goweb status
- negix 设置反向代理
进入 cd /etc/nginx/sites-available 然后创建 xxx.com 文件,然后写入
server {
server_name xxx.com www.xxx.com;
location / {
proxy_pass http://localhost:9990;
}
}
创建连接:
sudo ln -s /etc/nginx/sites-available/your_domain /etc/nginx/sites-enabled/your_domain
然后重新启动 nginx 服务:
sudo nginx -s reload
然后现在访问 http://xxx.com 就看到的服务返回的内容了;
有疑问加站长微信联系(非本文作者)