掘金 后端 ( ) • 2024-05-31 21:03

前言

大家好,我是老马。很高兴遇到你。

我们为 java 开发者实现了 java 版本的 nginx

https://github.com/houbb/nginx4j

如果你想知道 servlet 如何处理的,可以参考我的另一个项目:

手写从零实现简易版 tomcat minicat

手写 nginx 系列

如果你对 nginx 原理感兴趣,可以阅读:

从零手写实现 nginx-01-为什么不能有 java 版本的 nginx?

从零手写实现 nginx-02-nginx 的核心能力

从零手写实现 nginx-03-nginx 基于 Netty 实现

从零手写实现 nginx-04-基于 netty http 出入参优化处理

从零手写实现 nginx-05-MIME类型(Multipurpose Internet Mail Extensions,多用途互联网邮件扩展类型)

从零手写实现 nginx-06-文件夹自动索引

从零手写实现 nginx-07-大文件下载

从零手写实现 nginx-08-范围查询

从零手写实现 nginx-09-文件压缩

从零手写实现 nginx-10-sendfile 零拷贝

从零手写实现 nginx-11-file+range 合并

从零手写实现 nginx-12-keep-alive 连接复用

准备工作-HTTP 服务

我们简单起见,使用 node.js 启动一个简单的前端服务。

ubuntu 如何安装 node.js

  1. 更新包索引: 更新你的包索引列表以确保你安装的是最新版本的软件包。

    sudo apt update
    
  2. 安装 Node.js: 使用 apt 安装 Node.js 和 npm(Node.js 的包管理器)。

    sudo apt install -y nodejs npm
    

    这将安装最新的 Node.js 和 npm 版本。

  3. 验证安装: 安装完成后,你可以通过检查 Node.js 和 npm 的版本来验证安装是否成功。

    node -v
    npm -v
    

安装版本如下:

$ node -v
v12.22.9

$ npm -v
8.5.1

nodejs 创建一个 http 服务

Node.js 最简单的入门例子是一个基础的 Web 服务器,它使用 Node.js 内置的 http 模块来响应 HTTP 请求。

以下是创建这样一个服务器的步骤:

  1. 安装 Node.js:确保你已经在系统上安装了 Node.js。你可以通过在终端运行以下命令来检查 Node.js 是否已安装以及其版本号:

    node -v
    
  2. 创建一个新的 JavaScript 文件:在你的文本编辑器中,创建一个名为 app.js 的新文件。

  3. 编写代码:在 app.js 文件中,输入以下代码:

    const http = require('http'); // 引入 http 模块
    
    // 创建一个 HTTP 服务器
    const server = http.createServer((req, res) => {
      res.writeHead(200, {'Content-Type': 'text/plain'});
      res.end('Hello, World!\n'); // 响应请求并发送一个字符串
    });
    
    // 服务器监听 3000 端口
    server.listen(3000, '127.0.0.1', () => {
      console.log('Server running at http://127.0.0.1:3000/');
    });
    
  4. 运行你的服务器:在终端中,导航到 app.js 文件所在的目录,然后运行以下命令:

    node app.js
    
  5. 访问服务器

$ curl http://127.0.0.1:3000/
Hello, World!

想通过 nginx 来代理访问这个 http 服务,应该如何配置实现?

要通过 Nginx 代理访问你的 Node.js HTTP 服务,你需要在 Nginx 的配置文件中设置一个代理服务器。

以下是配置 Nginx 以代理 Node.js 服务的步骤:

先看一下 nginx 的配置

默认的配置如下:

cat /etc/nginx/nginx.conf

如下:

$ cat /etc/nginx/nginx.conf
user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
        worker_connections 768;
        # multi_accept on;
}

http {

        ##
        # Basic Settings
        ##

        sendfile on;
        tcp_nopush on;
        types_hash_max_size 2048;
        # server_tokens off;

        # server_names_hash_bucket_size 64;
        # server_name_in_redirect off;

        include /etc/nginx/mime.types;
        default_type application/octet-stream;

        ##
        # SSL Settings
        ##

        ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE
        ssl_prefer_server_ciphers on;

        ##
        # Logging Settings
        ##

        access_log /var/log/nginx/access.log;
        error_log /var/log/nginx/error.log;

        ##
        # Gzip Settings
        ##

        gzip on;

        # gzip_vary on;
        # gzip_proxied any;
        # gzip_comp_level 6;
        # gzip_buffers 16 8k;
        # gzip_http_version 1.1;
        # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

        ##
        # Virtual Host Configs
        ##

        include /etc/nginx/conf.d/*.conf;
        include /etc/nginx/sites-enabled/*;
}


#mail {
#       # See sample authentication script at:
#       # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
#
#       # auth_http localhost/auth.php;
#       # pop3_capabilities "TOP" "USER";
#       # imap_capabilities "IMAP4rev1" "UIDPLUS";
#
#       server {
#               listen     localhost:110;
#               protocol   pop3;
#               proxy      on;
#       }
#
#       server {
#               listen     localhost:143;
#               protocol   imap;
#               proxy      on;
#       }
#}

简单解释

这是一个 Nginx 的主配置文件,它包含了用于定义 Nginx 服务器行为的多种设置。

以下是配置文件中每一行的解释,其中注释行以 # 开头:

# 指定运行 Nginx 的用户和用户组
user www-data;

# 设置工作进程的数量,'auto' 会让 Nginx 根据 CPU 核心数自动设置
worker_processes auto;

# 指定 Nginx 进程的 PID 文件存放位置
pid /run/nginx.pid;

# 包含所有在 /etc/nginx/modules-enabled/ 目录下启用的模块配置文件
include /etc/nginx/modules-enabled/*.conf;

events {
    # 设置每个工作进程的最大连接数
    worker_connections 768;
    # 以下注释掉的选项可以启用或禁用多请求接受
    # multi_accept on;
}

http {
    ### 基础设置 ###

    # 开启高效文件传输模式
    sendfile on;
    # 开启 TCP 无推送选项,可以提高性能
    tcp_nopush on;
    # 设置类型hash桶的最大大小
    types_hash_max_size 2048;
    # 以下注释掉的选项可以关闭服务器版本号在错误页面和HTTP头部的显示
    # server_tokens off;

    # 设置服务器名称的hash桶大小
    # server_names_hash_bucket_size 64;
    # 禁止在重定向响应中出现服务器名称
    # server_name_in_redirect off;

    # 包含 MIME 类型配置文件
    include /etc/nginx/mime.types;
    # 默认的 MIME 类型
    default_type application/octet-stream;

    ### SSL 设置 ###

    # 设置 SSL/TLS 协议版本
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # 不支持 SSLv3,参考 POODLE 漏洞
    # 优先使用服务器端的加密套件
    ssl_prefer_server_ciphers on;

    ### 日志设置 ###

    # 定义访问日志的存放路径
    access_log /var/log/nginx/access.log;
    # 定义错误日志的存放路径
    error_log /var/log/nginx/error.log;

    ### Gzip 设置 ###

    # 开启 Gzip 压缩
    gzip on;
    # 以下注释掉的选项可以进一步配置 Gzip 压缩行为
    # gzip_vary on;
    # gzip_proxied any;
    # gzip_comp_level 6;
    # gzip_buffers 16 8k;
    # gzip_http_version 1.1;
    # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    ### 虚拟主机配置 ###

    # 包含 /etc/nginx/conf.d/ 目录下的所有配置文件
    include /etc/nginx/conf.d/*.conf;
    # 包含 /etc/nginx/sites-enabled/ 目录下的所有配置文件
    include /etc/nginx/sites-enabled/*;
}

#mail {
    # 下面的注释掉的链接提供了一个 Nginx 与 Apache/PHP 脚本进行 IMAP 认证的示例
    # 详见:http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
    #
    # auth_http localhost/auth.php;
    # pop3_capabilities "TOP" "USER";
    # imap_capabilities "IMAP4rev1" "UIDPLUS";
    #
    # server {
    #     listen     localhost:110;
    #     protocol   pop3;
    #     proxy      on;
    # }
    #
    # server {
    #     listen     localhost:143;
    #     protocol   imap;
    #     proxy      on;
    # }
#}

这个配置文件定义了 Nginx 服务器的基本运行参数,如用户、工作进程、PID 文件位置,以及事件处理、HTTP、SSL、日志、Gzip 压缩和虚拟主机包含的设置。被注释的部分可以通过去掉前面的 # 符号来启用。