通常我们的web应用程序部署的时候不会直接暴露,通过nginx反向代理,一是隐藏真实后端,二是通过nginx的epoll网络IO多路复用,获取高性能的网络访问。
今天我们分享个通过nginx代理go的后端web服务。
主要内容:
- nginx初始化配置
- go应用的初始化配置
- 部署实战
1.nginx初始化配置
nginx作为常用的web代理服务器,其优秀的性能自不必说,今天我们直接来看看nignx的docker化部署情况。
1.拉取镜像
docker pull nginx:latest
2.获取配置
先跑nginx容器,再把nginx的配置文件复制出来
pwd
// /root/ngx-go-web/ngx
ls
// conf conf.d html logs start.sh
docker run -d --name mynginx nginx:latest
docker cp /etc/nginx/nginx.conf ./conf/
3.停掉nginx容器
docker rm -f mynginx
4.查看nginx.conf
cat ./conf/nginx.conf
---
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log notice;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
#tcp_nopush on;
keepalive_timeout 65;
#gzip on;
include /etc/nginx/conf.d/*.conf;
server {
listen 80;
}
}
---
2.go应用的初始化配置
go用来编写代码,简单易上手,今天通过net/http
包,简单演示go的web应用。
web-server
mkdir go-http
ls
// go.mod server.go
新建文件后编写代码:
// server.go
package main
import (
"encoding/json"
"io"
"log"
"net/http"
)
func main() {
http.HandleFunc("/hello", hello)
http.HandleFunc("/login", login)
log.Println("HTTP server up at", "http://localhost:8080")
_ = http.ListenAndServe("0.0.0.0:8080", nil)
}
func hello(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello from go http server"))
}
func login(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(r.Body)
if err != nil {
w.Write([]byte("Bad request data."))
return
}
log.Println("req data:", string(body))
var data map[string]interface{}
_ = json.Unmarshal(body, &data)
username := data["username"]
passwd := data["password"]
if username == "username" && passwd == "password" {
w.Write([]byte(body))
return
}
w.Write([]byte("Bad login parameters."))
}
golang运行环境
pwd
// /root/ngx-go-web/go-http
vim Dockerfile
---
FROM golang:latest
ENV GO111MODULE=on
WORKDIR /opt/go-server
ADD . ./
RUN go build -o server .
EXPOSE 8080
ENTRYPOINT ["./server"]
---